Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all the special chars from a list [duplicate]

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

like image 411
devPie Avatar asked Oct 15 '25 19:10

devPie


2 Answers

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:

['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
like image 82
JANO Avatar answered Oct 17 '25 08:10

JANO


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']
like image 29
Siddharth Bhattacharjee Avatar answered Oct 17 '25 07:10

Siddharth Bhattacharjee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!