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

1    →  01
10   →  10
100  →  100

当前回答

你可以用f个字符串。

import numpy as np

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

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

00000001
00000124
00013566

其他回答

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

打印:

01
10
100

在Python >= 3.6中,您可以使用以下方法引入的新f-string简单地完成此操作:

f'{val:02}'

它输出名为val的变量,填充值为0,宽度为2。

对于你的具体例子,你可以在循环中很好地做到这一点:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

打印:

01 
10
100

有关f-字符串的更多信息,请参阅PEP 498,其中介绍了f-字符串。

你可以使用str.zfill:

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

打印:

01
10
100

这将是Python的方式,尽管为了清晰起见我会包括参数- "{0:0>2}".format(number),如果有人想要nLeadingZeros,他们应该注意他们也可以这样做:"{0:0>{1}}"。format(number, nLeadingZeros + 1)

你还可以:

'{:0>2}'.format(1)

它将返回一个字符串。