习题 6: 字符串(string)和文本

阅读原文

虽然你已经在程序中写过字符串了,你还没学过它们的用处。在这章习题中我们将使用复杂 的字符串来建立一系列的变量,从中你将学到它们的用途。首先我们解释一下字符串是什么 东西。

字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python 可以通过文本里的双引号 " 或者单引号 ' 识别出字符串来。这在你以前的 print 练习中你已经见过很多次了。如果你把单引号或者双引号括起来的文本放到 print 后面, 它们就会被 python 打印出来。

字符串可以包含格式化字符 %s,这个你之前也见过的。你只要将格式化的变量放到字符串 中,再紧跟着一个百分号 % (percent),再紧跟着变量名即可。唯一要注意的地方,是如果你想要 在字符串中通过格式化字符放入多个变量的时候,你需要将变量放到 ( ) 圆括号(parenthesis) 中,而且变量之间用 , 逗号(comma)隔开。就像你逛商店说“我要买牛奶、面包、鸡蛋、八宝粥”一样, 只不过程序员说的是"(milk, eggs, bread, soup)"。

我们将键入大量的字符串、变量、和格式化字符,并且将它们打印出来。我们还将练习使用简写 的变量名。程序员喜欢使用恼人的难度的简写来节约打字时间,所以我们现在就提早学会这个,这样你 就能读懂并且写出这些东西了。

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

What You Should See

$ python ex6.py
There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.
Isn't that joke so funny?! False
This is the left side of...a string with a right side.

Study Drills

  1. 通读程序,在每一行的上面写一行注解,给自己解释一下这一行的作用。
  2. 找到所有的"字符串包含字符串"的位置,总共有四个位置。
  3. 你确定只有四个位置吗?你怎么知道的?没准我在骗你呢。
  4. 解释一下为什么 we+ 连起来就可以生成一个更长的字符串。

Common Student Questions

What is the difference between %r and %s?
Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.
What's the point of %s and %d when you can just use %r?
The %r is best for debugging, and the other formats are for actually displaying variables to users.
I get the error TypeError: not all arguments converted during string formatting.
You need to make sure that the line of code is exactly the same. What happens in this error is you have more % format characters in the string than variables to put in them. Go back and figure out what you did wrong.
Why do you put ' (single-quotes) around some strings and not others?
Mostly it's because of style, but I'll use a single-quote inside a string that has double-quotes. Look at line 10 to see how I'm doing that.
If you thought the joke was funny could you write hilarious = True?
Yes, and you'll learn more about these boolean values in Exercise 27.

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""