String and Text in Python

String and Text in Python

While you have already been writing strings, you still do not know what they do. In this exercise, we create a bunch of variables with complex strings so you can see what they are for. First an explanation of strings.

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 ” (doublequotes) 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.

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


 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.

Study Drills

1. Go through this program and write a comment above each line explaining it.

2. Find all the places where a string is put inside a string. There are four places.

3. Are you sure there are only four places? How do you know? Maybe I like lying.

4. Explain why adding the two strings w and e with + makes a longer string.

What is the difference between %r and %s?

We use %r for debugging, since it displays the “raw” data of the variable, but we use %s and others for displaying to users.

What’s the point of %s and %d when you can just use %r?

The %r is best for debugging, and the other formats are for actually displaying variables to users.

Why do you put ‘ (single- quotes) around some strings and not others?

Mostly it’s because of style, but I’ll use a single- quote inside a string that has double- quotes. Look at line 10 to see how I’m doing that.