学习python的第四天

时间:2022-04-11 20:54:46

字符串和文本

字符串通常是用来展示给用户或是从程序中导出一段字符。Python是通过使用双引号或单引号识别字符串。字符串可以包含格式化字符%s,用法之前已经练习过:将格式化的变量放到字符串中,其后紧跟百分号%,再写变量名即可。多变量要使用括号,变量用逗号隔开。学会使用字符串和格式化字符可以节约时间。

练习部分

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

更多打印

这一节为练习,目的是巩固之前学到的东西。

练习部分

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,
print end7 + end8 + end9 + end10 + end11 + end12

在上一段的练习中,让我学到的一点是print "." * 10 这一行代码,又学会了一点。

打印,打印

练习部分

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."
)

%r的作用是输出所有内容。最后一行既有双引号又有单引号。在输入代码的时候字符串是被双引号括起来的,但在"But it didn't sing."字符串中包含了单引号,所以在输出的时候显示为双引号。字符串中包含有单引号的用双引号括起来用来区分;字符串中没有单引号在输出时显示单引号。