为什么输出不同?

时间:2013-06-01 14:45:50

标签: python python-2.7

阅读“以艰难的方式学习Python”,我试图修改练习6,以便了解会发生什么。最初它包含:

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 "I said: %r." % x  
print  "I also said: '%s'." % y

并生成输出:

I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.

为了看到在最后一行使用%s和%r之间的差异,我将其替换为:

print "I also said: %r." % y

现在获得输出:

I said: 'There are 10 types of people.'.
I also said: "Those who know binary and those who don't.".

我的问题是:为什么现在有双引号而不是单引号?

2 个答案:

答案 0 :(得分:6)

因为Python在引用方面很聪明。

您要求字符串表示%r使用repr()),它以合法的Python代码的方式呈现字符串。当您在Python解释器中回显值时,将使用相同的表示形式。

因为y包含单引号,Python会为您提供双引号,而不必转义该引号。

Python更喜欢使用单引号表示字符串表示,并在需要时使用double以避免转义:

>>> "Hello World!"
'Hello World!'
>>> '\'Hello World!\', he said'
"'Hello World!', he said"
>>> "\"Hello World!\", he said"
'"Hello World!", he said'
>>> '"Hello World!", doesn\'t cut it anymore'
'"Hello World!", doesn\'t cut it anymore'

只有当我使用两种类型的引号时,Python才开始使用转义代码(\')作为单引号。

答案 1 :(得分:3)

因为字符串中有一个引号。 Python正在补偿。