Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
iamshola Avatar asked Dec 21 '25 01:12

iamshola


1 Answers

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

like image 185
Martijn Pieters Avatar answered Dec 22 '25 17:12

Martijn Pieters