10

这个片段:

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.'

当其他三个项目在单引号中时,为什么"But it didn't sing."会被放在双引号中?

(此代码取自Learn Python the Hard Way 练习 8。

4

1 回答 1

10

Python很聪明;在生成表示时,它将对包含单引号的字符串使用双引号,以尽量减少转义:

>>> 'no quotes'
'no quotes'
>>> 'one quote: \''
"one quote: '"

在那里添加一个双引号,它将恢复为单引号并转义包含的任何单引号

>>> 'two quotes: \'\"'
'two quotes: \'"'
于 2012-08-11T19:40:53.247 回答