Skip to content

How to Remove Punctuation from a List in Python

If you have a Python list, and want to remove all punctuation, then you can do the following:

First get all punctuation by using string.punctuation

import string print(string.punctuation)
Code language: Python (python)

Output:

!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~
Code language: plaintext (plaintext)

Option 1 – Using for

import string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] new_words = [] for word in words: if word == "": words.remove(word) else: for letter in word: if letter in string.punctuation: word = word.replace(letter,"") new_words.append(word) print(new_words)
Code language: Python (python)

Option 2 – Using List Comprehensions

import string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] words = [''.join(letter for letter in word if letter not in string.punctuation) for word in words if word] print(words)
Code language: Python (python)

Option 3 – Using str.translate()

import string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] words = [word.translate(string.punctuation) for word in words if word] print(words)
Code language: Python (python)

See also  Find the Intersection of Two Arrays in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x