Sunday 18 December 2022

What does !r do in str() and repr()?

 According to the Python 2.7.12 documentation:

!s (apply str()) and !r (apply repr()) can be used to convert the value before it is formatted.

>>> import math
>>> print 'The value of PI is approximately {}.'.format(math.pi)
The value of PI is approximately 3.14159265359.
>>> print 'The value of PI is approximately {!r}.'.format(math.pi)
The value of PI is approximately 3.141592653589793.

Interestingly, the converted value is the output of repr(), rather than str().

>>> str(math.pi)
'3.14159265359'
>>> repr(math.pi)
'3.141592653589793'


from: https://stackoverflow.com/questions/38418070/what-does-r-do-in-str-and-repr