現(xiàn)在,我們學習一個字符串怎樣使用更復雜的格式化字符。下面的代碼看起來很復雜,但是如果你能將代碼分段,并給每一行加上注釋,你一樣可以弄明白代碼的意思。
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."
)
$ 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.'
仔細研究一下,并嘗試分析下我是怎樣在一個格式化字符串內部嵌套使用格式化的
1.自己檢查結果,記下你犯過的錯誤,并且在下個練習中盡量不犯同樣的錯誤。 2.注意最后一行程序中既有單引號又有雙引號,你覺得它是如何工作的?
可以用%s,但是盡量在做調試的時候使用%r。%r 顯示的是變量“原始”的數(shù)據(jù)值,%r 在打印的時候能夠重現(xiàn)它代表的對象。
Python 識別 True 和 False 表示真假的概念。如果你給它們加上引號,它們就變成了字符串,而不能用來判別真假了。在后面的習題 27 里,你會學到這些布爾值是如何運行的。
換成%s 試試,就能正常打印啦。
Python 可以用最有效的方式打印輸出字符串,而不是直接復制你寫的代碼。 你說的情況是很正常的,因為%r 常用來調試或檢查,因此沒必要將它輸出的很漂亮。
不要用 Python3.用 python2.7 會好一些,最好用 Python2.6。
不行,你現(xiàn)在需要學習使用命令行模式。這是你開始學習編程最好的方法,對你學習編程是很重要的。IDE 不利于你使用本書學習編程。