使用
i.replace(a, "")
只返回替换的字符串。您需要将结果重新分配到列表中。要做到这一点,您需要编辑
lst
带索引
i
:
def rmv_spc(lst, a):
a = str(a)
for i in range(len(lst)):
x = str(lst[i])
lst[i] = x.replace(a, "")
return lst
更好的方法是使用列表理解:
def rmv_spc(lst, a):
a = str(a)
return [str(x).replace(a, "") for x in lst]
这就是为什么
replace
作品:
# Assign x
>>> x = 'abc'
>>> x
'abc'
# Replace 'a' with nothing
>>> x.replace('a','')
'bc'
# That is the result that we wanted, but x is still the same
>>> x
'abc'
# So we need to say that x = that result
>>> x = x.replace('a','')
>>> x
'bc'