笨方法学Python 习题 8: 打印,打印

来源:互联网 发布:知乎 酒吧假酒 编辑:程序博客网 时间:2024/05/22 23:28
#!usr/bin/python# -*- coding:utf8 -*-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 rihgt.",    "But it didn't sing.",    "So I said goodnight."))print ("__________________________")formatter = "%s %s %s %s"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 rihgt.",    "But it didn't sing.",    "So I said goodnight."))


运行结果如下:

$ python ex8.py1 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.'$

加分习题

①自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。

大部分错误,都是最基础性的问题,括号冒号忘记加。

②注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?


常见问题回答

我应该使用 %s 还是 %r?

你应该使用 %s,只有在想要获取某些东西的 debug 信息时才能用到 %r。 %r 给你的是变量的“程序员原始版本”,又被称作“representation”。

为什么 “one” 要用引号,而 True 和 False 不需要?

因为 True 和 False 是 Python 的关键字,用来表示真假的意义。如果你加了引号,它们就变成了字符串,也就无法实现它们本来的功能了。习题 27 中会有详细说明。

我在字符中包含了中文(或者其它非 ASCII 字符),可是 %r 打印出的是乱码?

使用 %s 就行了。

为什么 %r 有时打印出来的是单引号,而我实际用的是双引号?

Python 会用最有效的方式打印出字符串,而不是完全按照你写的方式来打印。这样做对于 %r 来说是可以接受的,因为它是用作 debug 和排错,没必要非打印出多好看的格式。

为什么 Python 3 里这些都不灵?

别使用 Python 3 系列。使用 Python 2.7 或更新的版本,虽然 Python 2.6 应该也没问题。

可不可以使用 IDLE 运行代码?

不行。你应该学习使用命令行。命令行对学习编程很重要,而且是一个学习编程的绝佳初始环境。IDLE 在本书后面的章节里会让你失望的。



原创粉丝点击