Python:用零填充浮点数

dem*_*emi 1 python

如何用零填充双倍数到指定长度?

printf "{:.3}".format(0.12) # Doesn't pad
Run Code Online (Sandbox Code Playgroud)

我想得到

0.120
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 8

你需要一个f3:

In [19]: "{:.3f}".format(0.12)
Out[19]: '0.120'
Run Code Online (Sandbox Code Playgroud)

如果你没有指定任何类型浮点数,那么它'g'默认使用.

In [27]: "{:.20}".format(0.12)
Out[27]: '0.11999999999999999556'

In [28]: "{:.20g}".format(0.12)
Out[28]: '0.11999999999999999556'
Run Code Online (Sandbox Code Playgroud)

文档:http://docs.python.org/2/library/string.html#formatspec