Python Program to Remove Punctuations From a String

In this tutorial, we will see how to remove punctuations from a string in python. A string is essentially just a list of characters, so we will go through each character and assign an empty string to the character if it is punctuation.

The python concepts used are:

Defining the punctuations

All the punctuations that have to be removed are defined in the variable punctuation.
If you want to remove any other character, then it can also be included in the below variable.

punctuation = '''`[email protected]#$%^&*(){}[];:'".,/?'''

The triple quote (3 single quotes or 3 double quotes) in the start and end is compulsory.
If only one quote is given then the string will end at the single quote in the string and it will not be included, i.e. punctuation will not include punctuations from the single quote and including it, which in this case are  <‘ ” . , / ?>.
If two single quotes are given then an empty string is made in the start and punctuation will be an empty string.

Editing String by removing punctuations

for loop is used to traverse through all the characters of the input string.
If the given character belongs to punctuations that we have mentioned in the variable punctuation, then we will assign it an empty string and go to the next character. This is done using str.replace() function. If the character is not punctuation then we leave it unchanged.

# defining the punctuations to be removed 
punctuation = '''`[email protected]#$%^&*(){}[];:'".,/?''' 

input_str = "Hi!!$% this i&*&^s Cod()eSpeed{}y" 
# Taking Input from user 
# input_str = input("Enter string: ") 

# removing punctuations from the input string using a for loop 
# putting edited string in new_str
new_str = input_str
for char in input_str: 
    if char in punctuation: 
        new_str = new_str.replace(char,"") 

# display the unpunctuated string 
print(new_str)

This code is creating a new string called new_str. These changes can be made in the same string also by removing new_str and replacing the char in input_str instead of new_str. This can be seen in the code snippet below.

# defining the punctuations to be removed 
punctuation = '''`[email protected]#$%^&*(){}[];:'".,/?''' 

input_str = "Hi!!$% this i&*&^s Cod()eSpeed{}y" 
# Taking Input from user 
# input_str = input("Enter string: ") 

# removing punctuations from the input string using a for loop 
# the changes are made to input_str
for char in input_str: 
    if char in punctuation: 
        input_str = input_str.replace(char,"") 

# display the unpunctuated string 
print(input_str)

Output:

Hi this is CodeSpeedy

So, here it is.  A very simple program to remove punctuations from a string in Python.

Also read,

Count number of Vowels and Consonants in a string using Python
Remove multiple spaces from a string in Python

 

Leave a Reply

Your email address will not be published. Required fields are marked *