Understand Python string.punctuation and Remove Punctuation in a Sentence – Python Tutorial

By | June 20, 2020

string.punctuation is a python constant, which contains some punctuations in english. In this tutorial, we will introduce it and use it to remove punctuations in a text sentence.

What is string.punctuation?

string.punctuation is defined in python string package, it contain 32 punctuations used in english.

import string
print(string.punctuation)
print(len(string.punctuation))

Run this code, you will find string.punctuation is:

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

Understand Python string.punctuation and Remove Punctuation in a Sentence

How to remove all punctuations in a sentence?

It is easy to remove all punctuations by string.punctuation. Here is an example:

sentence = 'tutorialexample.com (TutorialExample) is a tutorial and example site.'

sen = [w for w in sentence if w not in string.punctuation]
print(sen)
sen = "".join(sen)
print(sen)

There are some punctuations in sentence, after removing all punctuations, we can get sen:

tutorialexamplecom TutorialExample is a tutorial and example site

Leave a Reply