如何显示小于两位数字的所有数字的前导零?

1    →  01
10   →  10
100  →  100

当前回答

或:

打印“{0:02d}”.format (1)

其他回答

在Python 2.6+和3.0+中,你可以使用format()字符串方法:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

或者使用内置的(单个数字):

print(format(i, '02d'))

有关新的格式化函数,请参阅PEP-3101文档。

width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

在Python 2(和Python 3)中,您可以执行:

number = 1
print("%02d" % (number,))

基本上%类似于printf或sprintf(参见文档)。


对于Python 3。+,同样的行为也可以通过format实现:

number = 1
print("{:02d}".format(number))

对于Python 3.6+,同样的行为可以通过f-strings实现:

number = 1
print(f"{number:02d}")

你可以使用str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

打印:

01
10
100

你可以用f个字符串。

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

这将打印常量长度8,并以前导0填充其余部分。

00000001
00000124
00013566