AppDividend
Latest Code Tutorials

Python Remove Punctuation: How to Strip Punctuation from a String

0

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)

Output

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

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)

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)

Output

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)

Output

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.

Then we are iterating all the characters of the string using for loop and replace the punctuation characters with empty characters.

That is it for Python remove punctuation tutorial.

See also

Python re.sub()

Python re.search()

Python regex replace()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.