Remove Punctuations From a String in Python

(Last Updated On: 12/01/2023)

Python Program to Remove Punctuations From a String Using for Loop

# Python program to remove custom punctuation from a string

# punctuation collection - you can mention any special characters you want to exclude from a string
punc_col = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# sample text
sample_text = "Hello, Newtum !is# ^the*@ b)e$st^ platform>< to Learn P>ython??"

print("Input String: " + sample_text)

# for loop will iterate through each character of the string and will check if it present in the punctuation collection variable
for c in sample_text:
    if c in punc_col:
        sample_text = sample_text.replace(c, "")

print("Final String: " + sample_text)

Output:

Input String: Hello, Newtum !is# ^the*@ b)e$st^ platform>< to Learn P>ython??
Final String: Hello Newtum is the best platform to Learn Python

Leave a Reply

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