在python函数中从列表中删除字符

2024-05-14 16:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图学习python中的函数,我遇到了下面这个问题的死胡同,我必须编写一个函数以获取字符串列表作为输入,删除特殊字符并返回一个包含干净字符串的列表

代码如下所示:

def cleanChar(a):
   a=[]
   b=[',','?','#','@','$','%','^','&','*','/']
   out_list=[]

   for x in a:
       for y in b:
           if y in x:
               x=x.replace(y,'')
               out_list.append
   return out_list


testq = ['#mahesh','%Po*hsi$','Iy&gdj']

test3=cleanChar(testq)
print(test3)

I get the out put as an empty list. What am I doing wrong here or what should have been my approach? Thanks in advance for the help.


Tags: the函数字符串代码in列表fordef
3条回答

您可以运行简单的列表理解来检查输入中的元素是否不在b中,然后使用join()返回结果字符串

def cleanChar(a):
    b=[',','?','#','@','$','%','^','&','*','/']
    return ''.join([element for element in a if element not in b])

testq = ['#mahesh','%Po*hsi$','Iy&gdj']

for i in testq:
    print(cleanChar(i))

输出

mahesh
Pohsi
Iygdj

我发现你的代码有三个问题

  1. 无需使用[]重新初始化函数参数a
  2. out_list.append应替换为out_list.append(x)
  3. out_list.append(x)必须与for y in b处于相同的缩进级别。这是因为我们只想在所有字符被替换后追加到输出列表

最后一个函数是这样的

>>> def cleanChar(a):
...     b = [",", "?", "#", "@", "$", "%", "^", "&", "*", "/"]
...     out_list = []
...     for x in a:
...         for y in b:
...             if y in x:
...                 x = x.replace(y, "")
...         out_list.append(x)
...     return out_list
...
>>> testq = ["#mahesh", "%Po*hsi$", "Iy&gdj"]
>>> test3 = cleanChar(testq)
>>> print(test3)
['mahesh', 'Pohsi', 'Iygdj']
import re
clean_testq = [re.sub('[^a-zA-Z]',"",each) for each in testq]
clean_testq

['mahesh', 'Pohsi', 'Iygdj']

相关问题 更多 >

    热门问题