Reputation: 191
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.)
Upvotes: 10
Views: 5219
Reputation: 1124758
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: \'"'
Upvotes: 10