我正试图学习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.
您可以运行简单的列表理解来检查输入中的元素是否不在
b
中,然后使用join()
返回结果字符串输出
我发现你的代码有三个问题
[]
重新初始化函数参数a
out_list.append
应替换为out_list.append(x)
out_list.append(x)
必须与for y in b
处于相同的缩进级别。这是因为我们只想在所有字符被替换后追加到输出列表李>最后一个函数是这样的
相关问题 更多 >
编程相关推荐