简体   繁体   中英

double quotes in string representation

This snippet:

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."
)

when run, prints this string:

'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

Why did "But it didn't sing." get put in double quotes when the other three items were in single quotes?

(This code is taken from Learn Python the Hard Way Exercise 8 .)

Python is clever; it'll use double quotes for strings that contain single quotes when generating the representation, to minimize escapes:

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

Add a double quote in there as well and it'll revert back to single quotes and escape any single quotes contained:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM