Python 为什么输出不同?

Python 为什么输出不同?,python,python-2.7,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 并生成

通过阅读《艰难地学习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.".

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

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

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

因为Python在引用方面很聪明

您要求的是%r使用的字符串表示形式,它以合法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才开始对单引号使用转义码\。

因为Python在引号方面很聪明

您要求的是%r使用的字符串表示形式,它以合法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才开始对单个引号使用转义码\。

很好地解释和演示了谢谢,请立即给出清晰的答案。现在我发现前面的作者在书中也提出了同样的观点。很好地解释和论证了谢谢你,给我一个清晰而直接的答案。现在我发现前面的作者在书中也提出了同样的观点。伊格纳西奥,谢谢你深思熟虑的回答。伊格纳西奥,谢谢你深思熟虑的回答。