PDF版 ePub版

# exercise6.字符串和文本

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

## 你看到的结果

\$ 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.

## 附加题

1.通读程序，并给每一行加上注释，解释下这行的作用。 2.找到所有的”字符串包含字符串”的位置，总共有四个位置。 3.你确定只有四个位置吗？你怎么知道的？也许我在骗你呢。 4.解释一下为什么用+连起来 w 和 e 就可以生成一个更长的字符串。

## 常见问题

### Q:%r 和 %s 有什么不同?

text = "I am %d years old." % 22 print "I said: %s." % text print "I said: %r." % text

I said: I am 22 years old.. I said: 'I am 22 years old.'. // %r 给字符串加了单引号