How do I make a list of strings withouth invalid characters in any of the strings?

Question:

For example, if I had this list of invalid characters:

invalid_char_list = [',', '.', '!']

And this list of strings:

string_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']

I would want to get this new list:

new_string_list = ['Hello', 'world', 'I', 'am', 'a', 'programmer']

withouth , or . or ! in any of the strings in the list because those are the characters that are in my list of invalid characters.

Asked By: Diego

||

Answers:

You can try looping through the string_list and replacing each invalid char with an empty string.

invalid_char_list = [',', '.', '!']
string_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']

for invalid_char in invalid_char_list:
    string_list=[x.replace(invalid_char,'') for x in string_list]

print(string_list)

The Output:

['Hello', 'world', 'I', 'am', 'a', 'programmer']
Answered By: E Joseph

You can use regex and create this pattern : [,.!] and replace with ''.

import re
re_invalid = re.compile(f"([{''.join(invalid_char_list)}])")
# re_invalid <-> re.compile(r'([,.!])', re.UNICODE)

new_string_list = [re_invalid.sub(r'', s) for s in string_list]
print(new_string_list)

Output:

['Hello', 'world', 'I', 'am', 'a', 'programmer']
  • [.,!] : Match only this characters (',', '.', '!') in the set
Answered By: I'mahdi

We can loop over each string in string_list and each invalid character and use String.replace to replace any invalid characters with ” (nothing).

invalid_char_list = [',', '.', '!']
   string_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']
   formatted_string_list = []
   for string in string_list:
       for invalid in invalid_char_list:
           string = string.replace(invalid, '')
       formatted_string_list.append(string)
Answered By: terrenana

You can use strip():

string_list = ['Hello,', ',world.?', 'I', 'am?', '!a,', 'programmer!!?']

new_string_list = [c.strip(',.!?') for c in string_list]

print(new_string_list)

#['Hello', 'world', 'I', 'am', 'a', 'programmer']
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.