Last Updated On By Khizer Ali
There are times when a certain response to a request is in string format with punctuation. Or the string received has undesired characters in it. It’s the programmer’s job to brush the unnecessary data like punctuation off the string. Remove punctuation from a string in Python is rather a common task and many can come across it frequently than expected.
In this article, I will highlight how to remove punctuation from a string python.
The following are considered and categorized as punctuation marks in python and most other languages. But few other punctuation character are sometimes included.
The list of punctuation marks that are given below includes question mark, exclamation mark, colon, semi-colon, mathematical symbols, and many more.
!"#$%&'()*+,-./:;?@[\]^_`{|}~
Using a for loop we can iterate over a string with punctuation. Following is an example in python.
# define punctuation
stringPunc= '!"#$%&'()*+,-./:;?@[\]^_`{|}~'
myString = "H!e)l%l*o( [email protected] [Le]aks!!, $/ ."
# remove punctuation from the string
replace = ""
for str in myString:
if str not in stringPunc:
replace = replace + str
# display the unpunctuated string
print(replace)
This code is an easy logic to remove punctuation from your string. stringPunc has all the defined punctuation and a variable myString is the string with punctuation.
Iterating myString to check if there are any punctuation and only considering those characters that are not in the variable stringPunc saving it in replace.
Output:
Hello Code Leaks
You can use replace function rather than concatenating each character.
stringPunc= '!"#$%&'()*+,-./:;?@[\]^_`{|}~'
myString = "H!e)l%l*o( [email protected] [Le]aks!! with replace, $/ ."
replace = ""
for str in myString:
if str in stringPunc:
myString=myString.replace(str, "")
print(myString)
Output:
Hello Code Leaks with replace
You can also remove punctuation using regex library.
import re
test_str = "CL, is best : for ! Code ;"
print("The original string is : " + test_str)
res = re.sub(r'[^\w\s]', '', test_str)
print("The string after punctuation filter : " + res)
Output:
In conclusion, we discussed how to remove punctuation in Python Programming Language with code snippet. Removing punctuation or any other character that you want can be done with only a few lines of code. Replacing the undesired character with an empty character “” by iterating it.