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

1    →  01
10   →  10
100  →  100

当前回答

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

其他回答

我是这样做的:

str(1).zfill(len(str(total)))

基本上zfill取你想加的前导零的个数,所以很容易取最大的数字,把它转换成字符串并得到长度,像这样:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

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

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

它内置在python中,具有字符串格式

f'{number:02d}'

所有这些都创建了字符串“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
x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果:

01
10
100

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