PythonMastery
Python programs · Strings · beginner

Remove punctuation from a string in Python

Strip commas, full stops, question marks and other punctuation from text with str.translate() and string.punctuation, or with a simple loop.

The string module has a ready-made string, string.punctuation, that holds the common punctuation characters. translate() can delete all of them in one call.

The program

python
import string

text = input("Enter some text: ")

table = str.maketrans("", "", string.punctuation)
print(text.translate(table))

Typed in this example: Hello, Linus! Is the build ready? (It's late.). Press Run to type your own.

output
Enter some text: Hello, Linus! Is the build ready? (It's late.)
Hello Linus Is the build ready Its late

How it works

This is the list of characters it removes:

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

With a loop

The same result, one character at a time. This version is easier to change, for example to keep some characters:

python
import string

text = "Wait... what?! Ada said: 'yes'."
clean = ""
for ch in text:
    if ch not in string.punctuation:
        clean += ch

print(clean)
output
Wait what Ada said yes

string.punctuation contains only the 32 ASCII punctuation characters. Curly quotes (“ ”) and the ellipsis character (…) are not in it, so add them to the list if your text uses them.

Learn the idea: Working with Strings, Loops: for, while, and the Pythonic Patterns