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

1    →  01
10   →  10
100  →  100

当前回答

x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果:

01
10
100

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

其他回答

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

打印:

01
10
100

使用格式字符串- http://docs.python.org/lib/typesseq-strings.html

例如:

python -c 'print "%(num)02d" % {"num":5}'
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

你还可以:

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

它将返回一个字符串。