71

As the title states, what is the difference between these two flags? It seems they both convert the value to a string using repr()? Also, in this line of code:

"{0!r:20}".format("Hello")  

What does the 0 in front of the !r do?

b_pcakes
  • 2,452
  • 3
  • 28
  • 45
  • 2
    The 0 means "use the 0th positional argument" - you only need it if you mean to use one of the position arguments more than once or if you need to support Python 2.6. `"{} {}"`.format(...)` gets automatically numbered so as to be treated as `"{0} {1}".format(...)` in Python 2.7 and 3.x. – lvc Oct 13 '15 at 08:03
  • Possible duplicate of [Python string formatting: % vs. .format](http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – Andrea Corbellini Oct 13 '15 at 08:45

1 Answers1

114

%r is not a valid placeholder in the str.format() formatting operations; it only works in old-style % string formatting. It indeed converts the object to a representation through the repr() function.

In str.format(), !r is the equivalent, but this also means that you can now use all the format codes for a string. Normally str.format() will call the object.__format__() method on the object itself, but by using !r, repr(object).__format__() is used instead.

There are also the !s and (in Python 3) !a converters; these apply the str() and ascii() functions first.

The 0 in front indicates what argument to the str.format() method will be used to fill that slot; positional argument 0 is "Hello" in your case. You could use named arguments too, and pass in objects as keyword arguments:

"{greeting!r:20}".format(greeting="Hello")  

Unless you are using Python 2.6, you can omit this as slots without indices or names are automatically numbered; the first {} is 0, the second {} takes the second argument at index 1, etc.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    Thanks, can you clarify what you meant by "this also means that you can now use all the format codes for a string"? – b_pcakes Oct 13 '15 at 08:15
  • 3
    The codes after the `:` colon are passed to the `object.__format__()` method and are thus type specific. Floating point numbers accept different formatting codes from strings. Thus if the object is a float, you'd use different formatting codes from when you add `!r`. – Martijn Pieters Oct 13 '15 at 08:23