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
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.
Enter some text: Hello, Linus! Is the build ready? (It's late.) Hello Linus Is the build ready Its late
How it works
str.maketrans("", "", string.punctuation)makes a translation table. Its third argument is a string of the characters to delete.text.translate(table)builds a new string with those characters left out. Letters, digits and spaces are kept.- The apostrophe is punctuation too, so "It's" becomes "Its". If you need to keep it, remove it from the list first:
string.punctuation.replace("'", "").
This is the list of characters it removes:
import string print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~With a loop
The same result, one character at a time. This version is easier to change, for example to keep some characters:
import string text = "Wait... what?! Ada said: 'yes'." clean = "" for ch in text: if ch not in string.punctuation: clean += ch print(clean)
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.