Removing Punctuation From Python List Items
Solution 1:
Assuming that your initial list is stored in a variable x, you can use this:
>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']
To remove the empty strings:
>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']
Solution 2:
Use string.translate:
>>> import string
>>> test_case = ['hello', '...', 'h3.a', 'ds4,']
>>> [s.translate(None, string.punctuation) for s in test_case]
['hello', '', 'h3a', 'ds4']
For the documentation of translate, see http://docs.python.org/library/string.html
Solution 3:
In python 3+ use this instead:
import string
s = s.translate(str.maketrans('','',string.punctuation))
Solution 4:
import string
print ''.join((x for x in st if x not in string.punctuation))
ps st is the string. for the list is the same...
[''.join(x for x in par if x not in string.punctuation) for par in alist]
i think works well. look at string.punctuaction:
>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
Solution 5:
To make a new list:
[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]