Software Engineering

Take away Punctuation from a Listing in Python

Take away Punctuation from a Listing in Python
Written by admin


You probably have a Python listing, and wish to take away all punctuation, then you are able to do the next:

First get all punctuation through the use of string.punctuation

import string
print(string.punctuation)

Output:

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

Possibility 1 – Utilizing for

import string
phrases = ["hell'o", "Hi,", "bye bye", "good bye", ""]
new_words = []
for phrase in phrases:
    if phrase == "":
        phrases.take away(phrase)
    else:
        for letter in phrase:
            if letter in string.punctuation:
                phrase = phrase.change(letter,"")   
        new_words.append(phrase)
print(new_words)

Possibility 2 – Utilizing Listing Comprehensions

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

Possibility 3 – Utilizing str.translate()

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

About the author

admin

Leave a Comment