Python Program to Remove Punctuations From a String – 2024

Hey guys, in this blog we will see a Python Program to Remove Punctuations From a String.

Code

# Python Program to Remove Punctuations From a String

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

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(my_str)
print(no_punct)

Output

Enter a string: Hey!!! How are you??
Hey!!! How are you??
Hey How are you
Enter a string: I am 22 years old... What about you?
I am 22 years old... What about you?
I am 22 years old What about you
Enter a string: testing !!@#$# 123
testing !!@#$# 123
testing  123
  • Defining a punctuation string as below:
  • punctuations = ”’!()-[]{};:'”\,<>./?@#$%^&*_~”’
  • Simply taking a string input from the user.
  • Then traversing through every character of our input string and checking if that character is present or not in the punctuation string we defined above.
  • If the character is not present in the punctuation string, add it in the new string, else ignore it.

Check out our other python programming examples

Leave a Reply

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