Python Remove Punctuation: How to Strip Punctuation from a String
The string.punctuation is a pre-initialized string in Python used as a string constant. To get the set of all the punctuations in Python, use the below code. Before that, you need to import the string module.
# import string library function import string # Storing the sets of punctuation in variable result result = string.punctuation # Printing the punctuation values print(result)
These are the punctuations used in Python String. But sometimes, we want to remove these punctuations from the string as per our requirement. Let’s see how to strip punctuations from a string.
Python remove punctuation
To remove punctuation efficiently in Python, use the combination of maketrans() and translate() function. The string translate() is a built-in Python method that returns the string where any defined characters are replaced with the character defined in a dictionary or a mapping table.
Python string maketrans() is a built-in mapping function that maps the characters of a string to its replacement or, in other words, its translation.
# import string library function import string # Define a string with punctuation s = "expecto. patronus. Charm?" # Use the combo of translate() and maketrans() method output = s.translate(str.maketrans('', '', string.punctuation)) print(output)
expecto patronus Charm
You can see that punctuation has been stripped from the string.
Remove punctuation using Regular Expression.
If you know regular expression better, you should use that and strip the punctuation from the string.
To use regular expressions in Python, import the re module.
import re s = "expecto. patronus. Charm?" op = re.sub(r'[^\w\s]','',s) print(op)
expecto patronus Charm
Our regular expression tells Python that remove all the punctuation characters from the string.
Strip punctuation using for loop
This approach is slow and not recommended but let’s see how to strip the punctuation from a string.
import string s = "expecto. patronus. Charm?" print("The original string is : " + s) punc = string.punctuation for d in s: if d in punc: op = s.replace(d, "") print("The striped string is: ", op)
The original string is : expecto. patronus. Charm? The striped string is: expecto. patronus. Charm
In this example, we are defining all the punctuation characters using string.punctuation.
That is it for Python remove punctuation tutorial.