1

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?

1
  • __repr__ adds extra quotes to string. __str__ doesn't. Commented Feb 20, 2017 at 22:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think I got it. So each formatter is executed individually that's why when it reached the third formatter which was %r, repr() was called. Am I correct?
@AhmedSamir: exactly.