雖然你已經(jīng)在程序中寫過字符串了,你還沒學(xué)過它們的用處。在這章習(xí)題中我們將使用復(fù)雜的字符串來建立一系列的變量,從中你將學(xué)到它們的用途。首先我們解釋一下字符串是什么 東西。
字符串通常是指你想要展示給別人的、或者是你想要從程序里“導(dǎo)出”的一小段字符。Python 可以通過文本里的雙引號 " 或者單引號 ' 識別出字符串來。這在你以前的 print 練習(xí)中你已經(jīng)見過很多次了。如果你把單引號或者雙引號括起來的文本放到 print 后面,它們就會被 python 打印出來。
字符串可以包含格式化字符 %s,這個(gè)你之前也見過的。你只要將格式化的變量放到字符串中,再緊跟著一個(gè)百分號 % (percent),再緊跟著變量名即可。唯一要注意的地方,是如果你想要在字符串中通過格式化字符放入多個(gè)變量的時(shí)候,你需要將變量放到 ( ) 圓括號(parenthesis)中,而且變量之間用 , 逗號(comma)隔開。就像你逛商店說“我要買牛奶、面包、雞蛋、八寶粥”一樣,只不過程序員說的是”(milk, eggs, bread, soup)”。
我們將鍵入大量的字符串、變量、和格式化字符,并且將它們打印出來。我們還將練習(xí)使用簡寫的變量名。程序員喜歡使用惱人的難度的簡寫來節(jié)約打字時(shí)間,所以我們現(xiàn)在就提早學(xué)會這個(gè),這樣你就能讀懂并且寫出這些東西了。
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.
$
|