python2:
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." )
你应该看到的结果:
python3代码:
formatter = "%r %r %r %r" print (formatter % (1,2,3,4)) print (formatter % ("oen","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." ) )
输出的结果为:
我猜此时你可能会有很多疑问,为什么输出的结果是这样的,以及“%r”和“%s”到底有什么区别?所以我的建议是可以试试重新给formatter赋值
formatter = "%s %s %s %s"
然后再重新运行上面的print,看看会输出什么样的结果,非常有意思。作者将在后面的习题中解答,我们可以带着疑问继续学习后面的习题。
加分习题
1. 自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。2. 注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?