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.我是否犯了一些愚蠢的错误?
也可以使用f
新格式:
>>> '{num:8.3f}'.format(num=1.98567)
' 1.986'
Run Code Online (Sandbox Code Playgroud)
如果没有格式类型,则默认为g
,并且精度被解释为总位数(不包括小数点前的0).在1
declimal点之前,它后面只显示2位数.
如果使用的g
是f
以下代码,则会看到与旧字符串格式相同的输出:
>>> '%8.3g' % (1.98567)
' 1.99'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
327 次 |
最近记录: |