2013-06-01 180 views
1

通过阅读“了解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 

,并产生输出:

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.'. 

为了看到使用%s和%R在上线之间的区别,我取代了它

,现在获得的输出:

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

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

回答

6

因为Python在引用时很聪明。

你问一个字符串表示%r使用repr()),其中介绍的方式,是合法的Python代码串。当您在Python解释器中回显值时,会使用相同的表示法。

由于y包含单引号,因此Python会为您提供双引号,无需转义该引号。

的Python更喜欢使用单引号的字符串表示,并在需要时以避免逃逸采用双:

>>> "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中开始使用转义码(\')为单引号。

+0

很好地解释和展示 –

+0

谢谢,清楚和直接的答案。现在我发现作者在书中提出了同样的观点。 – agtortorella

3

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

+0

Ignacio,谢谢你的深思熟虑的答案。 – agtortorella

相关问题