如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
当前回答
你可以使用str.zfill:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
打印:
01
10
100
其他回答
你还可以:
'{:0>2}'.format(1)
它将返回一个字符串。
你可以使用str.zfill:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
打印:
01
10
100
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
打印:
01
10
100
所有这些都创建了字符串“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
它内置在python中,具有字符串格式
f'{number:02d}'