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

1    →  01
10   →  10
100  →  100

当前回答

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

打印:

01
10
100

其他回答

python的方法是:

str(number).rjust(string_width, fill_char)

这样,如果原始字符串的长度大于string_width,则原始字符串将原封不动地返回。例子:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

结果:

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

结果:

01
10
100

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

Use:

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

或者使用数学模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

打印:

01
10
100

或者另一个解。

"{:0>2}".format(number)