字符串和文本
在这章习题中我们将使用复杂的字符串来建立一系列的变量,从中你将学到它们的用途。首先我们解释一下字符串是什么 东西。
字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python 可以通过文本里的双引号 " 或者单引号 ’ 识别出字符串来。这在你以前的 print 练习中你已经见过很多次了。如果你把单引号或者双引号括起来的文本放到 print 后面,它们就会被 python 打印出来。
字符串可以包含格式化字符 %s,这个你之前也见过的。你只要将格式化的变量放到字符串中,再紧跟着一个百分号 % (percent),再紧跟着变量名即可。唯一要
注意的地方,是如果你想要在字符串中通过格式化字符放入多个变量的时候,你需要将变量放到 ( ) 圆括号(parenthesis)中,而且变量之间用 , 逗号(comma)隔开。
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)
在这里犯了一个错误,(我用中文格式打出来的,会报错
运行结果:
更多打印练习
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."
))
运行结果
打印练习
# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print ("Here are the days: ", days)
print ("Here are the months: ", months)
print ("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
运行结果
\n是换行,下节会讲