Removing Punctuation from Python List Items

I have a list like

['hello', '...', 'h3.a', 'ds4,'] 

it should turn into

 ['hello', 'h3a', 'ds4'] 

and I want to remove only punctuation, leaving the letters and numbers integer. Punctuation is something in the string.punctuation constant. I know this gun is simple, but I'm a curious noobie in python, so ...

Thank giodamelio

+7
source share
5 answers

Assuming your original list is stored in 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 blank lines:

 >>> x = [s for s in x if s] >>> print(x) ['hello', 'h3a', 'ds4'] 
+20
source

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 translation documentation see http://docs.python.org/library/string.html

+8
source
 import string print ''.join((x for x in st if x not in string.punctuation)) 

ps st is a string. the list is the same ...

 [''.join(x for x in par if x not in string.punctuation) for par in alist] 

I think it works well. look at string.punctuaction:

 >>> print string.punctuation !"#$%&\'()*+,-./:;<=> ?@ [\\]^_`{|}~ 
+2
source

To create a new list:

 [re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings] 
+1
source

In python 3+, use this instead:

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

All Articles