简体   繁体   中英

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("{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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM