我想填充一些百分比值,以便小数点前总共有3个单位。有了整数,我可以使用'%03d' - 是否有相当于花车?

'%。3f'适用于小数点后但'%03f'不执行任何操作。

有帮助吗?

解决方案

'%03.1f'有效(1可以是任何数字,或空字符串):

>>> "%06.2f"%3.3
'003.30'

>>> "%04.f"%3.2
'0003'

请注意,字段宽度包括小数位数和小数位数。

其他提示

或者,如果您想使用 .format

              {:6.1f}
                ↑ ↑ 
                | |
# digits to pad | | # of decimal places to display

Copypasta: {:6.1f}

使用示例:

'Num: {:6.1f}'.format(number)

您也可以使用zfill。

str(3.3).zfill(5)
'003.3'

一个简短的例子:

var3= 123.45678
print(
    f'rounded1    \t {var3:.1f} \n' 
    f'rounded2    \t {var3:.2f} \n' 
    f'zero_pad1   \t {var3:06.1f} \n'  #<-- important line
    f'zero_pad2   \t {var3:07.1f}\n'   #<-- important line
    f'scientific1 \t {var3:.1e}\n'
    f'scientific2 \t {var3:.2e}\n'
)

提供输出

rounded1         123.5 
rounded2         123.46 
zero_pad1        0123.5 
zero_pad2        00123.5
scientific1      1.2e+02
scientific2      1.23e+02
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top