字符串表示中的双引号

Jos*_*tts 10 python python-2.7

这个片段:

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."
)
Run Code Online (Sandbox Code Playgroud)

运行时,打印此字符串:

'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
Run Code Online (Sandbox Code Playgroud)

"But it didn't sing."当其他三个项目都是单引号时,为什么要加上双引号?

(此代码取自Learn Python the Hard Way Exercise 8.)

Mar*_*ers 9

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

>>> 'no quotes'
'no quotes'
>>> 'one quote: \''
"one quote: '"
Run Code Online (Sandbox Code Playgroud)

在那里加上一个双引号,以及它会恢复到单引号和逃避包含的任何单引号:

>>> 'two quotes: \'\"'
'two quotes: \'"'
Run Code Online (Sandbox Code Playgroud)