Python program that uses the str.translate() method along with the string.punctuation property to remove punctuation from a given string

Created with Sketch.

Python program that uses the str.translate() method along with the string.punctuation property to remove punctuation from a given string

import string

def remove_punctuation(input_string):
    # Make a translator object to remove punctuation
    translator = str.maketrans('', '', string.punctuation)

    # Use this translator
    no_punct = input_string.translate(translator)
    return no_punct

# Example usage
s = "Hello! This is a sample sentence. How are you?"
print(remove_punctuation(s))

The function remove_punctuation(input_string) takes a string as an argument. The string.punctuation property is a string containing all ASCII punctuation characters. str.maketrans() method is used to create a translation table that can be used with str.translate() method. The translate() method returns a string where all characters specified in the translation table have been mapped to None. Finally, the function returns the modified string with no punctuation.

The example usage creates a string s that contains punctuation marks and then calls the remove_punctuation() function to remove the punctuation marks from the string and then it prints the modified string.

You could also use str.replace() method along with a loop, it’s not as efficient as the previous method but it’s more readable.

def remove_punctuation(input_string):
    for c in string.punctuation:
        input_string = input_string.replace(c, "")
    return input_string

In this method, the loop iterates over each punctuation character and replace it with an empty string.

Leave a Reply

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