pythonpython-3.xlistreplacewith

Replace elements group with a particular element in python3


I have a list of over 50 elements. These elements are lowercase and uppercase alphabets, numbers, special characters.

eg.

sample_list = ['1', '0', 'b', 'B', '2', '6', 'a', '7', '9', '5', 'c', 'd', '4', 'A', 'C', 'f', 'D', 'F', '3', 'C', '8', 'A', 'F', 'B', 'A', 'A', 'D'] 

I want to interchange particular elements with a special character. eg.

replacing `A,B,C and 1 with @
replacing `D,E,F and 2 with &
replacing `G,H,I and 3 with (

and so on, I have to replace a particular set of elements with 11 selected special characters. Like I replaced few selected elements with 3 of the special characters.

How to do it efficiently.


Solution

  • You could do it using translate method following way:

    sample_list = ['1', '0', 'b', 'B', '2', '6', 'a', '7', '9', '5', 'c', 'd', '4', 'A', 'C', 'f', 'D', 'F', '3', 'C', '8', 'A', 'F', 'B', 'A', 'A', 'D']
    t = ''.maketrans('ABC1DEF2GHI3','@@@@&&&&((((')
    out = [i.translate(t) for i in sample_list]
    print(out)
    

    Output:

    ['@', '0', 'b', '@', '&', '6', 'a', '7', '9', '5', 'c', 'd', '4', '@', '@', 'f', '&', '&', '(', '@', '8', '@', '&', '@', '@', '@', '&']
    

    maketrans method of str is used for creating translation table, just feed it with two equal length strs with first consisting of keys and second of values. translate method accept that table and replace characters accordingly, or left original intact if that there is not such key in table.

    EDIT: As noted by Olivier Melançon it can be used only if you want to replace 1 character with 1 character.