How to Remove Punctuation from a List in Python

0 min read 134 words

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)

Output:

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

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)

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)

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts