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
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.
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.
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().
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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With