如果列表中的数字不是必需的位数,我会尝试在每个数字前加上零。
lst = ['1234','2345']
for x in lst:
while len(x) < 5:
x = '0' + x
print(lst)
理想情况下,这将打印 ['012345', '02345']
请您参考如下方法:
您可以使用 zfill :
Pad a numeric string s on the left with zero digits until the given width is reached
lst = ['1234','2345']
[s.zfill(5) for s in lst]
# ['01234', '02345']
或者使用format具有填充和对齐的方法:
["{:0>5}".format(s) for s in lst]
# ['01234', '02345']
