2015-08-23 88 views
3

我在学习Python困难方式的exercise 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.' 

为什么在双引号中的第三句,为什么是单引号其他人呢?

回答

2

formatter正在使用%r,以便每个str打印在引号中。这样做的功能默认使用单引号作为分隔符,但如果它在字符串中看到一个单引号,并且字符串中没有双引号,则会切换为使用双引号作为分隔符。

例如,尝试:

print "%r" % '''This string has a ' and a " in it.''' 
2

您使用%r它调用__repr__方法。你似乎想要的是%s,它调用__str__方法。

在问题中的字符串中,您已经有一个';那就是为什么repr()"中给出它的引用。

+0

OP的问题是为什么报价不同,而不是为什么报价在那里。 –