Editor

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

remove_punctuation.py
import string
text = "Hello!!! How are you, Riya? I'm fine: thanks." # or: text = input("Enter a string: ")
result = ""
for ch in text:
if ch not in string.punctuation:
result += ch # keep letters, digits and spaces
print("Original:", text)
print("Without punctuation:", result)
print("Characters removed:", string.punctuation)
Output
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

  1. string.punctuation is a ready-made string of the 32 punctuation characters on an English keyboard, such as !, ?, , and ..
  2. The loop looks at each character and adds it to result only if it is not in that string.
  3. Spaces are not punctuation, so the words stay separated.
  4. 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()

Using translate()
import string
text = "Hello!!! How are you, Riya? I'm fine: thanks."
# A table that deletes every punctuation character
table = str.maketrans("", "", string.punctuation)
print("Without punctuation:", text.translate(table))
Output
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()

Using a comprehension and join()
import string
text = "Wait... what?! Really, (truly) amazing."
clean = "".join(ch for ch in text if ch not in string.punctuation)
print("Original:", text)
print("Clean: ", clean)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises