习题 8: 打印, 打印

阅读原文

现在,我们将会了解如何做一个字符串的更复杂的格式。此代码看起来复杂,但如果你在每一行上面进行注释,并合理设置中断,你就会明白了。

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. 自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。
  2. 注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?

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?
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. 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.

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""