通过阅读"以艰难的方式学习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
Run Code Online (Sandbox Code Playgroud)
并产生输出:
I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.
Run Code Online (Sandbox Code Playgroud)
为了查看最后一行中使用%s和%r之间的差异,我将其替换为:
print "I also said: %r." % y
Run Code Online (Sandbox Code Playgroud)
并获得现在的输出:
I said: 'There are 10 types of people.'.
I also said: "Those who know binary and those who don't.".
Run Code Online (Sandbox Code Playgroud)
我的问题是: 为什么现在有双引号而不是单引号?
因为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'
Run Code Online (Sandbox Code Playgroud)
只有当我使用两种类型的引号时,Python才开始使用转义码(\')作为单引号.