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

1    →  01
10   →  10
100  →  100

当前回答

如果处理的数字是一位数或两位数:

‘0’+ str (number)黑帽子-2:铝还是‘0那0’.format (number)黑-2:铝

其他回答

Use:

'00'[len(str(i)):] + str(i)

或者使用数学模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果:

01
10
100

在文档中阅读有关使用%格式化字符串的更多信息。

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

你可以用f个字符串。

import numpy as np

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

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

00000001
00000124
00013566

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