How to remove punctuation from a string in Python
Remove all punctuation characters from a string using the str.translate method and string.punctuation from the standard library.
Python code
10 linesimport string
def remove_punctuation(text: str) -> str:
return text.translate(str.maketrans("", "", string.punctuation))
if __name__ == "__main__":
sample = "Hello, world! It's a test... (with punctuation) - done?"
cleaned = remove_punctuation(sample)
print(f"Original: {sample}")
print(f"Cleaned: {cleaned}")
Output
Original: Hello, world! It's a test... (with punctuation) - done?
Cleaned: Hello world Its a test with punctuation done
How it works
The str.maketrans method creates a translation table that maps each character in the third argument to None, effectively deleting them. string.punctuation contains all ASCII punctuation characters such as !, ", #, and more. The translate method then applies this table to the string, removing every character listed in string.punctuation. This approach is fast and idiomatic, handling all common punctuation marks without needing a loop or regex. Note that it only covers ASCII punctuation; Unicode punctuation would require a different approach.
Common mistakes
- Forgetting that `translate` returns a new string; the original is unchanged
- Assuming `string.punctuation` includes Unicode punctuation marks
- Using a loop with `replace` which is inefficient for many punctuation characters
Variations
- Use a list comprehension with `str.isalnum()` to keep only letters and digits
- Use the `re.sub(r'[^\w\s]', '', text)` regex pattern to remove non-word, non-space characters
Real-world use cases
- Cleaning user input before storing or searching in a database.
- Normalizing text for natural language processing tasks like sentiment analysis.
- Stripping punctuation from generated slugs for URLs or file names.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.