开发者

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

开发者 https://www.devze.com 2023-02-18 08:04 出处:网络
>>>开发者_StackOverflow社区; import math >>> print \"{} {!s} {!r}\".format(math.pi, math.pi, math.pi)
>>>开发者_StackOverflow社区; 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消