By: Zed A. Shaw 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
- Data Science
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews