雖然你已經(jīng)在程序中寫(xiě)過(guò)字符串了,你還沒(méi)學(xué)過(guò)它們的用處。在這章習(xí)題中我們將使用復(fù)雜的字符串來(lái)建立一系列的變量,從中你將學(xué)到它們的用途。首先我們解釋一下字符串是什么 東西。
字符串通常是指你想要展示給別人的、或者是你想要從程序里“導(dǎo)出”的一小段字符。Python 可以通過(guò)文本里的雙引號(hào) " 或者單引號(hào) ' 識(shí)別出字符串來(lái)。這在你以前的 print 練習(xí)中你已經(jīng)見(jiàn)過(guò)很多次了。如果你把單引號(hào)或者雙引號(hào)括起來(lái)的文本放到 print 后面,它們就會(huì)被 python 打印出來(lái)。
字符串可以包含格式化字符 %s,這個(gè)你之前也見(jiàn)過(guò)的。你只要將格式化的變量放到字符串中,再緊跟著一個(gè)百分號(hào) % (percent),再緊跟著變量名即可。唯一要注意的地方,是如果你想要在字符串中通過(guò)格式化字符放入多個(gè)變量的時(shí)候,你需要將變量放到 ( ) 圓括號(hào)(parenthesis)中,而且變量之間用 , 逗號(hào)(comma)隔開(kāi)。就像你逛商店說(shuō)“我要買(mǎi)牛奶、面包、雞蛋、八寶粥”一樣,只不過(guò)程序員說(shuō)的是”(milk, eggs, bread, soup)”。
我們將鍵入大量的字符串、變量、和格式化字符,并且將它們打印出來(lái)。我們還將練習(xí)使用簡(jiǎn)寫(xiě)的變量名。程序員喜歡使用惱人的難度的簡(jiǎn)寫(xiě)來(lái)節(jié)約打字時(shí)間,所以我們現(xiàn)在就提早學(xué)會(huì)這個(gè),這樣你就能讀懂并且寫(xiě)出這些東西了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 string with a right side."
print w + e
|
1 2 3 4 5 6 7 8 | $ python ex6.py
There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.
Isn't that joke so funny?! False
This is the left side of...a string with a right side.
$
|