简体   繁体   English

从 python function 中的列表中删除字符

[英]Removing characters from a list in python function

I am trying to learn functions in python, I come across a dead end for below problem where I have to write a function to take a list of strings as input, remove special characters and return a list with clean strings.我正在尝试学习 python 中的函数,我遇到了以下问题的死胡同,我必须编写一个 function 以将字符串列表作为输入,删除特殊字符并返回包含干净字符串的列表。

Code looks as below:代码如下所示:

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.在此先感谢您的帮助。

I am seeing three issues with your code.我看到您的代码存在三个问题。

  1. No need to re-initialize the function parameter a with []无需用[]重新初始化 function 参数a
  2. out_list.append should be replaced with out_list.append(x) out_list.append应替换为out_list.append(x)
  3. out_list.append(x) must be in same indentation level as with for y in b . out_list.append(x)必须与for y in b缩进级别相同。 This is because we only want to append to the output list once all the characters are replaced.这是因为一旦所有字符都被替换,我们只想将 append 到 output 列表。

So your final function looks like this.所以你最终的 function 看起来像这样。

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

You can run a simple list comprehension to check if an element in your input is not in b , then use join() to return a string of the result.您可以运行一个简单的列表推导来检查输入中的元素是否不在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))

Outputs输出

mahesh
Pohsi
Iygdj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM