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."他の3つの項目が一重引用符で囲まれているのに、なぜ二重引用符で囲まれたのですか?

(このコードは、Learn Python the Hard Way Exercise 8から取得したものです。)

4

1 に答える 1

10

Pythonは賢いです。エスケープを最小限に抑えるために、表現を生成するときに一重引用符を含む文字列には二重引用符を使用します。

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

そこにも二重引用符を追加すると、一重引用符に戻り、含まれている一重引用符をエスケープします。

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