本节练习中我们将使用复杂的字符串来建立一系列的变量,来体会字符串的用处。
首先,我们还是要了解一下字符串这个概念。 字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python
可以通过文本里的双引号或者单引号识别出字符串来。这在咱之前的 print 练习中见过很多次了。如果你把单引号或者双引号括起来的文本放到 print
后面,它们就会被 python 打印出来。
字符串可以包含格式化字符 %s,这个咱之前也见过的。你只要将格式化的变量放到字符串中,再紧跟着一个百分号 %
(percent),再紧跟着变量名即可。唯一要注意的地方是如果你想要在字符串中通过格式化字符放入多个变量的时候,你需要将变量放到 ( ) 圆括号
(parenthesis) 中,而且变量之间用 , 逗号 (comma)
隔开。就像你逛商店说“我要买牛奶、面包、鸡蛋、八宝粥”一样,只不过程序员说的是”(milk, eggs, bread, soup)”。
我们将键入大量的字符串、变量、和格式化字符,并且将它们打印出来。我们还将练习使用简写的变量名。程序员喜欢使用令人生厌难度的简写来节约打字时间,所以我们现在就提早学会这个,这样你就能读懂并且写出这些东西了。
1 x = "There are %d types of people." % 10
2 binary = "binary"
3 do_not = "don't"
4 y = "Those who know %s and those who %s." % (binary, do_not)
5
6 print x
7 print y
8
9 print "I said: %r." % x
10 print "I also said: '%s'." % y
11
12 hilarious = False
13 joke_evaluation = "Isn't that joke so funny?! %r"
14
15 print joke_evaluation % hilarious
16
17 w = "This is the left side of..."
18 e = "a string with a right side."
19
20 print w + e
如果上面的操作都没问题,你将看到下面的结果:
1 $ python ex6.py
2 There are 10 types of people.
3 Those who know binary and those who don't.
4 I said: 'There are 10 types of people.'.
5 I also said: 'Those who know binary and those who don't.'.
6 Isn't that joke so funny?! False
7 This is the left side of...a string with a right side.
8 $
免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。