Python Program to Remove Punctuation from a String
Beginner · Strings
Punctuation marks are characters such as full stops, commas, question marks and quotes. Removing them leaves only letters, digits and spaces, which is a common first step before counting or comparing words. This program keeps every character that is not a punctuation mark.
Program
Original: Hello!!! How are you, Riya? I'm fine: thanks.
Without punctuation: Hello How are you Riya Im fine thanks
Characters removed: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~How it works
string.punctuationis a ready-made string of the 32 punctuation characters on an English keyboard, such as!,?,,and..- The loop looks at each character and adds it to
resultonly if it is not in that string. - Spaces are not punctuation, so the words stay separated.
- The apostrophe counts as punctuation too, so I'm becomes Im; take it out of the check if you want to keep it.
Other ways to write it
Using translate()
Without punctuation: Hello How are you Riya Im fine thanks
The third argument of str.maketrans() lists characters to delete, and translate() applies the table in one fast pass. This is the usual way in real code.
Using a comprehension and join()
Original: Wait... what?! Really, (truly) amazing. Clean: Wait what Really truly amazing
The expression inside join() picks out the characters to keep, and "".join() glues them back into one string.
Try it yourself
Add .lower() to the result so the clean text is also all small letters, ready for counting words.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Remove Spaces from a String
- Count the Frequency of Words in a String
- Count Letters, Digits and Spaces in a String
- Remove Vowels from a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises