多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
# 习题 6: 字符串(string)和文本 虽然你已经在程序中写过字符串了,你还没学过它们的用处。在这章习题中我们将使用复杂的字符串来建立一系列的变量,从中你将学到它们的用途。首先我们解释一下字符串是什么 东西。 字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python 可以通过文本里的双引号 " 或者单引号 ' 识别出字符串来。这在你以前的 print 练习中你已经见过很多次了。如果你把单引号或者双引号括起来的文本放到 print 后面,它们就会被 python 打印出来。 字符串可以包含格式化字符 %s,这个你之前也见过的。你只要将格式化的变量放到字符串中,再紧跟着一个百分号 % (percent),再紧跟着变量名即可。唯一要注意的地方,是如果你想要在字符串中通过格式化字符放入多个变量的时候,你需要将变量放到 () 圆括号(parenthesis)中,而且变量之间用 , 逗号(comma)隔开。就像你逛商店说“我要买牛奶、面包、鸡蛋、八宝粥”一样,只不过程序员说的是”(milk, eggs, bread, soup)”。 我们将键入大量的字符串、变量、和格式化字符,并且将它们打印出来。我们还将练习使用简写的变量名。程序员喜欢使用恼人的难度的简写来节约打字时间,所以我们现在就提早学会这个,这样你就能读懂并且写出这些东西了。 <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19&#13; 20</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>x = "There are %d types of people." % 10&#13; binary = "binary"&#13; do_not = "don't"&#13; y = "Those who know %s and those who %s." % (binary, do_not)&#13; &#13; print x&#13; print y&#13; &#13; print "I said: %r." % x&#13; print "I also said: '%s'." % y&#13; &#13; hilarious = False&#13; joke_evaluation = "Isn't that joke so funny?! %r"&#13; &#13; print joke_evaluation % hilarious&#13; &#13; w = "This is the left side of..."&#13; e = "a string with a right side."&#13; &#13; print w + e&#13; </pre> </div> </td> </tr></tbody></table> ### 你应该看到的结果 <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre>1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>$ python ex6.py&#13; There are 10 types of people.&#13; Those who know binary and those who don't.&#13; I said: 'There are 10 types of people.'.&#13; I also said: 'Those who know binary and those who don't.'.&#13; Isn't that joke so funny?! False&#13; This is the left side of...a string with a right side.&#13; $&#13; </pre> </div> </td> </tr></tbody></table> ### 加分习题 1. 通读程序,在每一行的上面写一行注解,给自己解释一下这一行的作用。 1. 找到所有的”字符串包含字符串”的位置,总共有四个位置。 1. 你确定只有四个位置吗?你怎么知道的?没准我在骗你呢。 1. 解释一下为什么 w 和 e 用 + 连起来就可以生成一个更长的字符串。