如何使用 format 属性在 python 3.2 中获取整数以将 0 填充到固定宽度? 示例:
a = 1
print('{0:3}'.format(a))
给出我想要的“1”而不是“001”。在 python 2.x 中,我知道这可以使用
print "%03d" % number.
我检查了 python 3 字符串文档,但没能得到它。
http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language
谢谢。
最佳答案
在宽度前加上 0
:
>>> '{0:03}'.format(1)
'001'
此外,在最新版本的 Python(不确定是哪个,但至少 2.7 和 3.1)中,您不需要位置标记:
>>> '{:03}'.format(1)
'001'
关于string - 固定宽度数字格式化python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6869999/