Search code examples
python-2.7formatter

Formatters in Python


I have this line of code:

formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, formatter) print formatter % ( "I had this thing for you.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." )<<<

and the output for the last 4 lines is:

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

I want to understand why does the third sentence display in double quotation while the others are in single quotation.

I have tried removing the double quotation, but it does not yield the expected result.


print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing for you.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."

Solution

  • It's because you have apostrophe ' inside the string. If you remove it, it will be printed as 'But it didnt sing.' It's to differentiate between string limits. It would be somewhat confusing if it was printed with ': 'But it didn't sing.'

    PS. If you add both ' and " signs to your string then thing get even more interesting. Try yourself.