Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!
文章主要分为三个部分:
- 原文—摘录至《笨方法学Python》第三版
- 学习中遇到的问题
- 问题的解决方法
- 附加练习
原文—摘录至《笨方法学Python》第三版
ex6.py & ex8.py
# ex6.py
x="There are %d types of people." %10
binary="binary"
do_not="don't"
y="Those who know %s and those who %s." %(binary,do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." %y
hilarious=False
joke_evaluation="Isn't that joke so funny?! %r "
print joke_evaluation % hilarious
w="This is the left side of ..."
e="a sting with a right side."
print w+e
# ex8.py
fomatter="%r %r %r %r"
print fomatter %(1,2,3,4)
print fomatter %("one","two","three","four")
print fomatter %(True,False,False,True)
print fomatter %(fomatter,fomatter,fomatter,fomatter)
print fomatter %(
"I had this thing.",
"That you could type up right."
"But it didn't sing."
"So I said goodnight."
)
遇到的问题
- ex8.py 的代码中 %r打印出来的是单引号,但是实际上用的双引号
python会用最有效的方式打印出字符串,而不是完全按照你写的方式来打印。 True
和False
是Pyhthon的关键字,用来表示真和假的概念。如果加了引号,就变成了字符串,无法实现原来的功能。%r
的作用
%r
是用来调试(debug)比较好,因为它会显示变量的原始数据,而%s
、%d
等符号是用来向用户显示输出的。
附加练习
以下摘录自原文
- 每一行加一段注释
- 最后一行输出既有单引号又有双引号,你觉得这背后的机制是什么?