user4099680
user4099680

Reputation:

Why does printing formatters in python differ when it's not all the same?

When I run this code

formatter = "%s %s %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.",
   "That you could type up right.",
   "But it didn't sing.",
   "So I said goodnight."
)

The output of this line

print formatter % (formatter, formatter, formatter, formatter)

is

%s %s %r %r %s %s %r %r '%s %s %r %r' '%s %s %r %r'

Now I understand that in python we use %r for debugging reasons and specified formatters like %s for the user thats why the (' ') is added when %r is used. What I don't understand is why is the only the first 2 without single quotes and not all of them?! How was that line executed briefly?

Upvotes: 1

Views: 41

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

%s interpolates the result of str() on the object, while %r takes the output of repr() on the same object.

For strings, a string literal syntax is produced by repr():

>>> s = 'foo bar'
>>> repr(s)
"'foo bar'"
>>> print(repr(s))
'foo bar'

That's because for the Python built-in objects, repr() will usually produce the same syntax that'll recreate the value. For integers or booleans, the str() and repr() versions just happen to look the same so you won't see a difference.

But when you interpolate formatter, a string, into formatter itself, you get two times the str() output, and two times the repr() output, and these differ.

Upvotes: 1

Related Questions