Exercise 8: Printing, Printing

We will now see how to do a more complicated formatting of a string. This code looks complex, but if you do your comments above each line and break each thing down to its parts, you'll understand it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
)

What You Should See

$ python ex8.py
1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

Study this carefully and try to see how I put the formatter inside the formatter.

Study Drills

  1. Do your checks of your work, write down your mistakes, and try not to make them on the next exercise.
  2. Notice that the last line of output uses both single-quotes and double-quotes for individual pieces. Why do you think that is?

Common Student Questions

Should I use %s or %r for formatting?
You should use %s and only use %r for getting debugging information about something. The %r will give you the "raw programmer's" version of variable, also known as the "representation."
Why do I have to put quotes around "one" but not around True or False?
That's because Python recognizes True and False as keywords representing the concept of true and false. If you put quotes around them then they are turned into strings and won't work right. You'll learn more about how these work in Exercise 27.
I tried putting Chinese (or some other non-ASCII characters) into these strings, but %r prints out weird symbols.
Use %s to print that instead and it'll work.
Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?
Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.
Why doesn't this work in Python 3?
Don't use Python 3. Use Python 2.7 or better, although Python 2.6 might work fine.
Can I use IDLE to run this?
No, you should learn to use the command line. It is essential to learning programming and is a good place to start if you want to learn about programming. IDLE will fail for you when you get further in the book.

Video