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

1    →  01
10   →  10
100  →  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-字符串。

其他回答

或者另一个解。

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

所有这些都创建了字符串“01”:

>python -m timeit "'{:02d}'.format(1)"
1000000 loops, best of 5: 357 nsec per loop

>python -m timeit "'{0:0{1}d}'.format(1,2)"
500000 loops, best of 5: 607 nsec per loop

>python -m timeit "f'{1:02d}'"
1000000 loops, best of 5: 281 nsec per loop

>python -m timeit "f'{1:0{2}d}'"
500000 loops, best of 5: 423 nsec per loop

>python -m timeit "str(1).zfill(2)"
1000000 loops, best of 5: 271 nsec per loop

>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32

你可以使用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)

Use:

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

或者使用数学模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)