开发者

Missing type to str.format() behavior

According to the Python docs here, when leaving the type out, it defaults to a type of 'g' for floating point arguments.

However,

print(开发者_StackOverflow中文版"{0:.2}".format(14.9))

prints "1.5e+01", while

print("{0:.2g}".format(14.9))

prints "15"

Is this simply an issue of the documentation being incorrect or is there another reason for it?


According to the source code, this is a documentation bug. The correct description for the behaviour without a floating point specifier is "like 'g', but always with at least one digit after the decimal point".


You linked the documentation of Python 2.7, but you actually used Python 3.x. In the documentation of Python 3.x, the behaviour is correctly documented.

The Python 2.7 documentation is faulty anyway:

>>> "{0:.2}".format(14.9)
'15.0'

>>> "{0:.2g}".format(14.9)
'15'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜