新的Python打印格式语句返回不同的结果.为什么?

Ron*_*ohn 3 python string string-formatting python-2.7

Python 2.7.5+

新样式"{X.Yf}".format(num)似乎不像旧样式'%X.Yf'%(num).谁能解释一下?

>>> '%8.3f' % (0.98567)
'   0.986'
>>> '%8.3f' % (1.98567)
'   1.986'

>>> '{num:8.3}'.format(num=0.98567)
'   0.986'
>>> '{num:8.3}'.format(num=1.98567)
'    1.99'
Run Code Online (Sandbox Code Playgroud)

请注意旧样式如何在小数点后显示3位数,但新样式有时会打印2,有时为3.我是否犯了一些愚蠢的错误?

Mar*_*ers 6

也可以使用f新格式:

>>> '{num:8.3f}'.format(num=1.98567)
'   1.986'
Run Code Online (Sandbox Code Playgroud)

如果没有格式类型,则默认为g,并且精度被解释为位数(不包括小数点前的0).在1declimal点之前,它后面只显示2位数.

如果使用的gf以下代码,则会看到与旧字符串格式相同的输出:

>>> '%8.3g' % (1.98567)
'    1.99'
Run Code Online (Sandbox Code Playgroud)