通读“艰难地学习 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 在引用方面很聪明。
您正在请求一个字符串表示(%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 才开始对单引号使用转义码 (\')。
