习题 6:字符串和文本
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
# 如果在字符串中通过格式化字符放入多个变量,需要将变量放到()中,变量之间用逗号隔开
y = "Those who know %s and those who is %s." % (binary, do_not)
print(x)
print(y)
print("I said: %r." % x) # %r 的含义是:不管什么都打印出来
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)
%r 同来做调试(debug)比较好,因为它会显示变量的原始数据(raw data),而其他格式符则是用来向用户显示输出的。
习题 7:更多打印
print("Mary had a little lamb.")
print("Its fleece was white as %s." % 'snow')
print("And everywhere that Mary went.")
print("." * 10)
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end9 + end10 + end11 + end12)
习题 8:打印, 打印
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."))
常见问题回答:
为什么“one”要用引号,而 True 和 False 不需要?
因为 True 和 False 是 Python 的关键字,用来表示真和假的概念。
为什么 %r 有时打印出来的是单引号,问我实际用的是双引号?
Python 会用最有效的方式打印出字符串,而不是完全按照你写的方式来打印。这样做对于 %r 来说是可以接受的,因为它是用于调试和排错的,没必要非打印出多好看的格式。
习题 9:打印,打印,打印
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.
""")