Chr*_*ris 5 python string-formatting
我正在尝试在'nan'浮点数上使用string.format.
这是python文档中 'g'选项的描述.
一般格式.这会将数字打印为定点数,除非数字太大,在这种情况下,它会切换为'e'指数表示法.无穷大和NaN值分别被格式化为inf,-inf和nan.
这就是我在解释器(Python 2.6)中尝试它的原因:
>>> print "{0:g}".format(float('nan'))
-1.#IND
Run Code Online (Sandbox Code Playgroud)
据我了解文档,输出应为"nan".
这是一个错误还是我做错了?
repr(float)修复了Python 2.6和Python 3.0; 见http://bugs.python.org/issue1635 ; 然而str.format直到2.7分支才得到修复; 请参阅http://hg.python.org/cpython/rev/c5e0d9beebf9和http://bugs.python.org/issue1580.
我建议看看是否"{0!r}"适合你; 这应该调用到非断repr码.
如果您需要使用"{0:g}"格式规范,您可以尝试子类化float和覆盖__format__:
class FixFloat(float):
def __format__(self, format_spec):
return 'nan' if math.isnan(self) else float.__format__(self, format_spec)
"{0:g}".format(FixFloat(1.2345e9))
'1.2345e+09'
"{0:g}".format(FixFloat(float('nan')))
'nan'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2259 次 |
| 最近记录: |