Removing Punctuation From Python List Items

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


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
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~

In python 3+ use this instead:

import string
s = s.translate(str.maketrans('','',string.punctuation))

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']

Tags:

Python

List