Precise definition of float string formatting?

旧时模样 提交于 2019-12-07 16:25:26

问题


Is the following behavior defined in Python's documentation (Python 2.7)?

>>> '{:20}'.format(1e10)                                                        
'       10000000000.0'
>>> '{:20g}'.format(1e10)
'               1e+10'

In fact, the first result surprises me: the documentation indicates that not indicating the format type ('f', 'e', etc.) for floats is equivalent to using the general format 'g'. This example shows that this does not seem to be the case, so I'm confused.

Maybe this is related to the fact that "A general convention is that an empty format string ("") produces the same result as if you had called str() on the value."? In fact:

>>> str(1e10)
'10000000000.0'

However, in the case of the {:20} format, the format string is not empty (it is 20), so I'm confused.

So, is this behavior of {:20} defined precisely in the documentation? Is the precise behavior of str() on floats precisely defined (str(1e11) has an exponent, but not str(1e10)…)?

PS: My goal is to format numbers with an uncertainty so that the output is very close to what floats would give (presence or not of an exponent, etc.). However, I'm having a hard time finding the exact formatting rules.

PPS: '{:20}'.format(1e10) gives a result that differs from the string formatting '{!s:20}'.format(1e10), where the string is flushed to the left (as usual for string) instead of to the right.


回答1:


As @blckknght explains in comments, '{:20}' specifies a string width of 20; to specify float precision you need a decimal point before it: {:.20} or {:.20g}.

As to why the number is formatted as it is, OP said it: "A general convention is that an empty format string ("") produces the same result as if you had called str() on the value." That's what you're getting, space-padded as per the format string (it's empty as to the number format, and the format can accommodate the full str representation).



来源:https://stackoverflow.com/questions/16525924/precise-definition-of-float-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!