在 Python 中添加一个字符串
Prepend a string in Python
如果列表中的数字不是必需的位数,我会尝试在每个数字前加上零。
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']
您的代码无法完成这项工作,因为 python 中的字符串是不可变的,请参阅此处了解更多信息 Why doesn't calling a Python string method do anything unless you assign its output?
在这种情况下,您可以这样枚举:
lst = ['1234','2345', "23456"]
for i, l in enumerate(lst):
if len(l) < 5:
lst[i] = '0' + l
print(lst)
['01234', '02345', '23456']
你可以这样做:
>>> lst = ['1234','2345']
>>> lst = ['0' * (5 - len(i)) + i for i in lst]
>>> print(lst)
['01234', '02345']
您可以像这样使用列表理解:
>>> ['0' * (5-len(x)) + x for x in lst]
['01234', '02345']
或者 list
+ map
尝试:
>>> list(map(lambda x: '0' * (5-len(x)) + x, lst))
['01234', '02345']
最终,这是完成工作的答案的组合。
lst = ['1234','2345']
newlst = []
for i in lst:
i = i.zfill(5)
newlst.append(i)
print(newlst)
如果我的示例不清楚,我深表歉意。感谢所有提供答案的人!
如果列表中的数字不是必需的位数,我会尝试在每个数字前加上零。
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']
您的代码无法完成这项工作,因为 python 中的字符串是不可变的,请参阅此处了解更多信息 Why doesn't calling a Python string method do anything unless you assign its output?
在这种情况下,您可以这样枚举:
lst = ['1234','2345', "23456"]
for i, l in enumerate(lst):
if len(l) < 5:
lst[i] = '0' + l
print(lst)
['01234', '02345', '23456']
你可以这样做:
>>> lst = ['1234','2345']
>>> lst = ['0' * (5 - len(i)) + i for i in lst]
>>> print(lst)
['01234', '02345']
您可以像这样使用列表理解:
>>> ['0' * (5-len(x)) + x for x in lst]
['01234', '02345']
或者 list
+ map
尝试:
>>> list(map(lambda x: '0' * (5-len(x)) + x, lst))
['01234', '02345']
最终,这是完成工作的答案的组合。
lst = ['1234','2345']
newlst = []
for i in lst:
i = i.zfill(5)
newlst.append(i)
print(newlst)
如果我的示例不清楚,我深表歉意。感谢所有提供答案的人!