float字符串格式的精确定义? [英] Precise definition of float string formatting?
问题描述
是否在Python文档(Python 2.7)中定义了以下行为?
>>> '{:20}'。format(1e10)
'10000000000.0'
>>> '{:20g}'。format(1e10)
'1e + 10'
事实上,第一个结果令我惊讶:文件表示不指示浮点数的格式类型('f','e'等)等同于使用通用格式'g'。这个例子表明,这似乎并不是这样,所以我很困惑。
也许这与一般约定是空的格式字符串()产生的结果与您对该值调用str()时的结果相同。事实上:
>>> str(1e10)
'10000000000.0'
但是,在 {:20}
格式,格式字符串是 not 为空(它是 20
),所以我'b
$ b
那么,是否在文档中精确地定义了 pythonhosted.org/uncertainties/rel =nofollow>带有不确定性的数字 {:20}
的行为?精确定义的浮点数( str(1e11)
)上的 str()
是否具有指数,但不是< PS:我的目标是格式(1e10) ...)?$ /
PPS:'{:20}'。format(1e10)
给出的结果不同于字符串格式'{!s:20}'.format(1e10)
,其中字符串被刷新到左边(像通常的字符串),而不是右边。
正如@blckknght在注释中解释的, {:20}
指定了一个字符串宽度20;要指定浮点精度,需要在它之前有一个小数点: {:. 20}
或 {:. 20g}
。
至于为什么这个数字格式化,OP说:一个通用的惯例是空格式字符串()产生相同的结果,如果你已经调用了str()的值。这就是你得到的,根据格式字符串进行空格填充(数字格式是空的,格式可以容纳完整的 str
表示) p>
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.
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).
这篇关于float字符串格式的精确定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!