By: Zed A. Shaw Viewed: 1387 times Printer Friendly Format
A string is usually a bit of text you want to display to someone, or “export” out of the program you are writing. Python knows you want something to be a string when you put either " (double-quotes) or ’ (single-quotes) around the text.
You saw this many times with your use of print when you put the text you want to go to the string inside " or ’
after the print. Then Python prints it.
Strings may contain the format characters you have discovered so far. You simply put the formatted variables in the string, and then a % (percent) character, followed by the variable. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside ( ) (parenthesis) separated by , (commas). It’s as if you were telling me to buy you a list of items from the store and you said, “I want milk, eggs, bread, and soup.” Only as a programmer we say, “(milk, eggs, bread, soup)”.
We will now type in a whole bunch of strings, variables, formats, and print them. You will also practice using short abbreviated variable names. Programmers love saving themselves time at your expense by using annoying cryptic variable names, so let’s get you started being able to read and write them early on.
1 x = "There are %d types of people." % 10
2 binary = "binary"
3 do_not = "don't"
4 y = "Those who know %s and those who %s." % (binary, do_not)
6 print x
7 print y
9 print "I said: %r." % x
10 print "I also said: '%s'." % y
12 hilarious = False
13 joke_evaluation = "Isn't that joke so funny?! %r"
15 print joke_evaluation % hilarious
17 w = "This is the left side of..."
18 e = "a string with a right side."
20 print w + e
What You Should See
$ python ex6.py
There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.
Isn't that joke so funny?! False
This is the left side of...a string with a right side.
Most Viewed Articles (in python )
Latest Articles (in python)
Comment on this tutorial
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews