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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

10 lines
Python 3.9+
import 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

stdout
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

  1. Use a list comprehension with `str.isalnum()` to keep only letters and digits
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.