10
votes

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

1
Look at the word "didn't" --> it contains a single quote. - Michael
Because that is the only one string that has a single quote inside it. So, it is not possible a string like 'But it didn't sing'. - Valdir Stumm Junior
but why does python do that? =o. Is there a reason for it? - Joseph Potts
Since the original string contains a single quote, Python is adding double-quotes around the string to make it unambiguous. In other words, with double quotes around the whole string, there is no possibility of the ' being mis-interpreted as the beginning or end of another string. - Robert Harvey
Why is this too localized? It is simply giving a reproducible example. - David Robinson

1 Answers

9
votes

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: \'"'