[英]Printing in both double and single quotes
我正在练习艰难学习Python的练习8 ,我不明白为什么print
功能中的某些行用单引号或双引号打印。
该计划内容如下:
formatter = "%r %r %r %r"
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
输出如下:
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
为什么第三句用双引号括起来,为什么其他的用单引号?
formatter
使用%r
以便每个str
都用引号打印。 执行此操作的函数默认使用单引号作为分隔符,但如果它在字符串中看到单引号,并且字符串中没有双引号,则它将切换为使用双引号作为分隔符。
例如,尝试:
print "%r" % '''This string has a ' and a " in it.'''
您正在使用调用__repr__
方法的%r
。 你似乎想要的是调用__str__
方法的%s
。
在有问题的字符串中你已经有了'
; 这就是为什么repr()
在"
。 "
引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.