def rmv_spc(lst,a):
a = str(a)
for i in lst:
i = str(i)
i.replace(a,"")
return lst
print(rmv_spc([343, 893, 1948, 3433333, 2346],3))
嘗試了多種方法,但輸出總是相同的串列。
uj5u.com熱心網友回復:
這會奏效,
def rmv_spc(lst,a):
for i in range(len(lst)):
lst[i] = str(lst[i]).replace(str(a),"")
return lst
print(rmv_spc([343, 893, 1948, 3433333, 2346],3))
輸出 -
['4', '89', '1948', '4', '246']
您的代碼已成功替換串列中每個專案的字符,但它沒有用新專案替換舊專案。
uj5u.com熱心網友回復:
使用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'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462205.html
標籤:Python python-3.x
