从python中的项列表中删除特殊字符

时间:2017-11-15 07:36:42

标签: python string list special-characters

my_list = ["on@3", "two#", "thre%e"]

我的预期输出是,

out_list = ["one","two","three"]

我不能简单地将strip()应用于这些项目,请提供帮助。

4 个答案:

答案 0 :(得分:3)

这是另一种解决方案:

import re
my_list= ["on@3", "two#", "thre%e"]
print [re.sub('[^a-zA-Z0-9]+', '', _) for _ in my_list]

<强>输出:

['on3', 'two', 'three']

答案 1 :(得分:2)

使用str.translate() method将相同的翻译表应用于所有字符串:

removetable = str.maketrans('', '', '@#%')
out_list = [s.translate(removetable) for s in my_list]

str.maketrans() static method是制作翻译地图的有用工具;前两个参数是空字符串,因为您没有替换字符,只删除。第三个字符串包含您要删除的所有字符。

演示:

>>> my_list = ["on@3", "two#", "thre%e"]
>>> removetable = str.maketrans('', '', '@#%')
>>> [s.translate(removetable) for s in my_list]
['on3', 'two', 'three']

答案 2 :(得分:1)

试试这个:

l_in = ["on@3", "two#", "thre%e"]
l_out = [''.join(e for e in string if e.isalnum()) for string in l_in]
print l_out
>['on3', 'two', 'three']

答案 3 :(得分:0)

使用两个for循环

l = ['@','#','%']
out_list = []
for x in my_list:
    for y in l:
        if y in x:
            x = x.replace(y,'')
            out_list.append(x)
            break

使用列表理解

out_list = [ x.replace(y,'')  for x in my_list for y in l if y in x ]

假设3中的on@3是拼写错误,输出将为on@3,而不是预期的one