字符串表示中的双引号

时间:2012-08-11 19:33:18

标签: 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."
)

运行时,打印此字符串:

'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 Exercise 8。)

1 个答案:

答案 0 :(得分:9)

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

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

中添加双引号,它将恢复为单引号并转义所包含的任何单引号:

>>> 'two quotes: \'\"'
'two quotes: \'"'