2015-08-23 66 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的問題是爲什麼報價不同,而不是爲什麼報價在那裏。 –