通过阅读“艰苦学习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 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
因为Python在引用方面很聪明。
您正在要求一个字符串表示形式(%ruse 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/150
提交
取消