此片段:
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."
被置于双引号中?
答案 0 :(得分:9)
Python很聪明;在生成表示时,它将对包含单引号的字符串使用双引号,以最小化转义:
>>> 'no quotes'
'no quotes'
>>> 'one quote: \''
"one quote: '"
在中添加双引号,它将恢复为单引号并转义所包含的任何单引号:
>>> 'two quotes: \'\"'
'two quotes: \'"'