How can I remove special characters from a list of elements in python?

Viewed 41652

I have a list of elements containing special characters. I want to convert the list to only alphanumeric characters. No special characters. my_list = ["on@3", "two#", "thre%e"]

my expected output is,

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

I cannot simply apply strip() to these items, please help.

4 Answers

Here is another solution:

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

output:

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

Use the str.translate() method to apply the same translation table to all strings:

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

The str.maketrans() static method is a helpful tool to produce the translation map; the first two arguments are empty strings because you are not replacing characters, only removing. The third string holds all characters you want to remove.

Demo:

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

try this:

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

Using two for loops

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

Using list comprehension

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

Assuming 3 in on@3 is a typo, the output will be on@3 and not one as expected

Related