Search code examples
pythonstringlistspecial-characters

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


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.


Solution

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