Python – Remove Punctuation from String
Last Updated :
07 Jan, 2025
Improve
In this article, we will explore various methods to Remove Punctuations from a string.
Using str.translate() with str.maketrans()
str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation tables.
s = "Hello, World! Python is amazing."
# Create translation table
import string
translator = str.maketrans('', '', string.punctuation)
# Remove punctuation
clean_text = s.translate(translator)
print(clean_text)
Output
Hello World Python is amazing
Explanation:
str.maketrans('', '', string.punctuation)
creates a mapping to remove all punctuation.- The
translate()
method applies this mapping efficiently. - The punctuation is stripped, leaving only the text.
Let’s explore some more ways and see how we can remove punctuation from string.
Using Regular Expressions (re.sub)
This method is slightly less efficient but very flexible as it Works for complex patterns, not just punctuation.
s = "Text cleaning? Regex-based! Works fine."
# Removing punctuation
import re
clean = re.sub(r'[^\w\s]', '', s)
print(clean)
Output
Text cleaning Regexbased Works fine
Explanation:
- Regex Pattern:
[^\w\s]
matches any character that is not a word character or whitespace. - re.sub() replaces matched punctuation with an empty string.
Using List Comprehension
A concise way to remove punctuation is by iterating through the string and including only alphanumeric characters and spaces.
s = "Hello, World! Python is amazing."
import string
# Filter out punctuation
clean = ''.join([char for char in s if char not in string.punctuation])
print(clean)
Output
Hello World Python is amazing
Explanation:
- char.isalnum() Checks if the character is alphanumeric.
- char.isspace() retains spaces between words.
- ‘ ‘.join(…)combines the filtered characters into a single string.
Using filter()
filter() function can also be used for removing punctuation, providing a clean and functional approach.
s = "Filtering... Is it clean now?"
# Removing punctuation
import string
clean = ''.join(filter(lambda x: x not in string.punctuation, s))
print(clean)
Output
Filtering Is it clean now
Explanation:
- string.punctuation used to identify punctuation characters.
- filter() retains only characters that are not in
string.punctuation
. - ‘ ‘.join(…)combines the filtered characters.