Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Punctuation From Python List Items

Tags:

python

list

I have a list like

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

this should turn into

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

and i want to remove only the punctuation leaving the letters and numbers intact. Punctuation is anything in the string.punctuation constant. I know that this is gunna be simple but im kinda noobie at python so...

Thanks, giodamelio

like image 899
giodamelio Avatar asked Dec 06 '10 21:12

giodamelio


People also ask

How do you remove punctuation NLTK?

To get rid of the punctuation, you can use a regular expression or python's isalnum() function. It does work: >>> 'with dot. '. translate(None, string.

How do you punctuate lists in Python?

In Python, string. punctuation will give the all sets of punctuation. Parameters : Doesn't take any parameter, since it's not a function. Returns : Return all sets of punctuation.

How do you remove an item from a list in Python?

We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. pop() is also a method of list. We can remove the element at the specified index and get the value of that element using pop().


2 Answers

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']
like image 143
Mark Byers Avatar answered Oct 26 '22 20:10

Mark Byers


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

like image 45
Josh Bleecher Snyder Avatar answered Oct 26 '22 20:10

Josh Bleecher Snyder