25

如何使用 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

谢谢。

4

3 回答 3

62

用 a 前缀宽度0

>>> '{0:03}'.format(1)
'001'

此外,您不需要在最新版本的 Python 中使用位置标记(不确定是哪个,但至少是 2.7 和 3.1):

>>> '{:03}'.format(1)
'001'
于 2011-07-29T07:43:16.127 回答
11

更好的:

number=12
print(f'number is equal to {number:03d}')
于 2019-12-14T03:25:15.757 回答
9

有内置的字符串方法.zfill用于填充 0-s:

>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'
于 2019-05-26T08:09:45.217 回答