如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
如何显示小于两位数字的所有数字的前导零?
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 >>>
其他回答
x = [1, 10, 100]
for i in x:
print '%02d' % i
结果:
01
10
100
在文档中阅读有关使用%格式化字符串的更多信息。
你可以用f个字符串。
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
这将打印常量长度8,并以前导0填充其余部分。
00000001
00000124
00013566
Use:
'00'[len(str(i)):] + str(i)
或者使用数学模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
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
它内置在python中,具有字符串格式
f'{number:02d}'