如何格式化具有给定精度和零填充的浮点数?

tom*_*ton 6 python string string.format python-3.x

我看了几十个类似的问题 - 我很高兴能得到另一个答案的链接 - 但我想在python 3.3中填零一个浮点数

n = 2.02
print( "{?????}".format(n))
# desired output:
002.0200
Run Code Online (Sandbox Code Playgroud)

浮点的精度很容易,但我不能得到零填充.什么进入????的

the*_*eye 10

您可以使用格式说明符,如下所示

>>> "{:0>8.4f}".format(2.02)
'002.0200'
>>> print("{:0>8.4f}".format(2.02))
002.0200
>>> 
Run Code Online (Sandbox Code Playgroud)

这里,8代表总宽度,.4代表精度.并且0>意味着字符串必须右对齐并0从左侧填充.