iamshola
iamshola

Reputation: 128

Python String Format Explanation

I saw this in a code,

print('Job: {!r}, {!s}'.format(5,3))

and the answer is

Job: 5, 3

how does {!r} evaluate? Does it have any special meaning there?

Upvotes: 3

Views: 236

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122132

!r calls repr() on the value before interpolating.

For integers, the str(), default format() and repr() output doesn't differ. For other types, such as strings, the difference is more visible:

>>> print('Repr of a string: {!r}'.format("She said: 'Hello, world!'"))
Repr of a string: "She said: 'Hello, world!'"

Note that quotes were included.

See the Format String Syntax; the character after ! specifies the conversion applied to the value. The default is no conversion, but you can use either !r or !s to convert a value to its repr() representation or str() string output, respectively.

You'd usually use conversion when either dealing with a type that doesn't specify an explicit __format__() method (such as bytes), when explicitly formatting to the repr() output (very helpful for debug output), or when you have to handle a mix of types.

Upvotes: 9

Related Questions