Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is {!s} meaningful in format()?

Tags:

python

>>> import math
>>> print "{} {!s} {!r}".format(math.pi, math.pi, math.pi)
3.14159265359 3.14159265359 3.141592653589793

When is the !s inside {} meaningful?

Or in other words, when is calling str() on a format() argument meaningful?

like image 995
ripper234 Avatar asked Dec 07 '25 09:12

ripper234


1 Answers

Whenever the type to be printed implements __format__ in an an unsuitable way for your purpose. In this case, you can use !s or !r (and I think there is even !a) to specify an alternate formatter.

You certainly won't need it for printing floating-point numbers, but probably for custom types.

like image 157
Alexander Gessler Avatar answered Dec 09 '25 23:12

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!