Python Program to Remove Punctuations From a String


Levels of difficulty: / perform operation:

Sometimes, we may wish to break a sentence into a list of words. In such cases, we may first want to clean up the string and remove all the punctuation marks. Here is an example of how it is done.

Source Code:

# Program to all punctuation from the string provided by the user

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# take input from the user
my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)

Output:

Enter a string: "Hello!!!", he said ---and went.
Hello he said and went

In this program, we first define a string of punctuations. Then, we iterate over the provided string using a for loop. In each iteration, we check if the character is a punctuation mark or not using the membership test. We have an empty string to which we add (concatenate) the character if it is not a punctuation. Finally, we display the cleaned up string.

Other Related Programs in python

  1. Python Program to Remove Punctuations From a String