Py学习  »  Python

替换python中在我的代码中不起作用的函数

Anis Ghosh • 3 年前 • 1320 次点击  
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))

尝试了多种方法,但输出总是相同的列表。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132711
 
1320 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Freddy Mcloughlan
Reply   •   1 楼
Freddy Mcloughlan    3 年前

使用 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'
Ishan Shishodiya
Reply   •   2 楼
Ishan Shishodiya    3 年前

这会管用的,

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']

您的代码成功地替换了列表中每个项目的字符,但没有将旧项目替换为新项目。