Removing especial characters from a string list in Python?

Question:

I have two lists; the first a string list with names (name_list) in it and a second list with especial characters (char_list). What I’m looking for to do is to remove all the especial characters that are found in any placement of each letter in each name from the name_list.

Psdt. I know that there are other ways to do so (like using reg) but in this case I’m attempting to do it without using such especial functions/libraries, just .replace() at much like I’ve been trying shown below:

Say this is my full especial characters list:

char_list = ['%',']','(','/','&','?','¨','+']

Those characters above are the ones that I’m looking for to replace in the name_list, say these are the names:

name_list = ['LAURE]N', 'NIC%HOL/AS', 'nichol?as', '(Vic(t¨oria', 'H+AROLD']

And this is my attempt using loops and conditionals but I still haven’t got it quite right:

for index, value in enumerate(name_list):
 
  if char_list[index + 1] in value:
    name_list[index + 1].lower().replace(char_list[index + 1], "")
  
  print(set(name_list))

I’m printing set(name_list) and including .lower() because besides removing/replacing the chars I’m also trying to retrieve the unique names from the name_list

This is of course giving me an error because I haven’t figured out yet so any help to do it properly this way or very close without other libraries is very well received! 🙂

Asked By: Supernova

||

Answers:

You don’t have to do the in check. Just do the replaces.

char_list = '%](/&?¨+'
name_list = ['LAURE]N', 'NIC%HOL/AS', 'nichol?as', '(Vic(t¨oria', 'H+AROLD']
new_list = []
for n in name_list:
    for c in char_list:
        n = n.replace(c,'')
    new_list.append(n)
Answered By: Tim Roberts