4

i have a list of strings with some strings being the special characters what would be the approach to exclude them in the resultant list

list = ['ben','kenny',',','=','Sean',100,'tag242']

expected output = ['ben','kenny','Sean',100,'tag242']

please guide me with the approach to achieve the same. Thanks

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
devPie
  • 71
  • 5
  • 1
    This should be a comment but look at this thread: https://stackoverflow.com/questions/47301795/how-can-i-remove-special-characters-from-a-list-of-elements-in-python – snowmoss Jan 20 '22 at 12:57

3 Answers3

11

The string module has a list of punctuation marks that you can use and exclude from your list of words:

import string

punctuations = list(string.punctuation)

input_list = ['ben','kenny',',','=','Sean',100,'tag242']
output = [x for x in input_list if x not in punctuations]

print(output)

Output:

['ben', 'kenny', 'Sean', 100, 'tag242']

This list of punctuation marks includes the following characters:

['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
JANO
  • 2,995
  • 2
  • 14
  • 29
3

It can simply be done using the isalnum() string function. isalnum() returns true if the string contains only digits or letters, if a string contains any special character other than that, the function will return false. (no modules needed to be imported for isalnum() it is a default function)

code:

list = ['ben','kenny',',','=','Sean',100,'tag242']
olist = []
for a in list:
   if str(a).isalnum():
      olist.append(a)
print(olist)

output:

['ben', 'kenny', 'Sean', 100, 'tag242']
0
my_list = ['ben', 'kenny', ',' ,'=' ,'Sean', 100, 'tag242']
stop_words = [',', '=']

filtered_output = [i for i in my_list if i not in stop_words]

The list with stop words can be expanded if you need to remove other characters.

liveware
  • 72
  • 5