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

1    →  01
10   →  10
100  →  100

当前回答

我是这样做的:

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 2.6+和3.0+中,你可以使用format()字符串方法:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

或者使用内置的(单个数字):

print(format(i, '02d'))

有关新的格式化函数,请参阅PEP-3101文档。

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

打印:

01
10
100

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

f'{number:02d}'

我是这样做的:

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
>>>