Remove Punctuations from a String Using Python

In these Python program examples, you will learn how to remove all the punctuations from a given string.

The two methods are as follows

  • Using replace method
  • Using Regular Expressions

Using string.replace method

In this program we use replace method to replace all the presented punctuations with the empty string “”.

def remove_punctuation_replace(input_string):
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    for punctuation in punctuations:
        input_string = input_string.replace(punctuation, "")
    return input_string

input_string = "Hello, World! How are you doing today?"
print(remove_punctuation_replace(input_string))

Output

Hello World How are you doing today

Using Regular Expression

import re

def remove_punctuation_regex(input_string):
    return re.sub(r'[^\w\s]','',input_string)

input_string = "The quick brown fox jumps over the lazy dog!"
print(remove_punctuation_regex(input_string))

Here in the code we import the “re” python module to remove punctuation from the input string. Here function “remove_punctuation_regex” takes the input string as an argument and applies a regular expression pattern to match and remove all non-alphanumeric and non-space characters from the string.

The “sub” method from the “re” module is used to substitute the matched characters with an empty string.

Output

The quick brown fox jumps over the lazy dog

Leave a Comment