Use text.translate(str.maketrans("", "", string.punctuation))—which builds a C-level lookup table once via str.maketrans() and strips every ASCII punctuation character in a single linear pass ($O(n)$) without regular-expression backtracking or Python-level character loops.
Basic Example
import string
# 1. Build the translation table ONCE at module/function startup:
PUNCT_TABLE = str.maketrans("", "", string.punctuation)
text = "Hello, world! Isn't Python's `str.translate()` super-fast? (Yes: 100%.)"
# 2. Recommended: Strip all ASCII punctuation in C speed
clean_text = text.translate(PUNCT_TABLE)
print(clean_text)
# Output: Hello world Isnt Pythons strtranslate superfast Yes 100
Key Details & Edge Cases
- Cache the
str.maketrans()table—do NOT rebuild it inside a loop:str.maketrans("", "", string.punctuation)constructs a dictionary mapping every punctuation Unicode ordinal toNone. Creating it once outside your loop makes.translate()~5x–10x faster thanre.sub()or generator expressions.
- Note that
.translate()deletes punctuation without inserting spaces ("super-fast"$\rightarrow$"superfast"):- If words are separated only by punctuation without whitespace (e.g.,
"end.Start"or"foo/bar"), removing punctuation directly merges them into"endStart"/"foobar". When tokenizing text for NLP or search, replace punctuation with a space instead ofNone(str.maketrans({c: " " for c in string.punctuation})) and normalize whitespace with" ".join(clean.split()).
- If words are separated only by punctuation without whitespace (e.g.,
- Handling Unicode punctuation (
—,…,“ ”,‘ ’,« »,،,؟) beyond ASCIIstring.punctuation:string.punctuationonly includes the 32 ASCII punctuation characters (!"#$%&'()*+,-./:;<=>?@[\]^_~`). To strip all Unicode punctuation categories (`P*`, such as em-dashes, smart quotes, ellipses, and non-Latin punctuation), build the table once using `unicodedata.category()`:import sys import unicodedata UNICODE_PUNCT_TABLE = dict.fromkeys( i for i in range(sys.maxunicode + 1) if unicodedata.category(chr(i)).startswith("P") ) print("“Hello”—world…".translate(UNICODE_PUNCT_TABLE)) # Output: Helloworld
- Keeping specific characters (such as apostrophes
'or hyphens-):- Exclude characters you want to preserve when constructing
string.punctuation:keep = "'-" punct_to_strip = "".join(c for c in string.punctuation if c not in keep) CUSTOM_TABLE = str.maketrans("", "", punct_to_strip)
- Exclude characters you want to preserve when constructing
- Bytes vs.
str(bytes.translate):- When processing raw ASCII
bytesbuffers (b"hello, world!"), useb_text.translate(None, delete=string.punctuation.encode("ascii"))for zero-decoding C speed.
- When processing raw ASCII
Comparison of Punctuation-Removal Methods in Python
| Method | Relative Speed | Handles Unicode Punctuation? | Can Replace with Spaces Instead of Deleting? | Best Used When |
|---|---|---|---|---|
text.translate(str.maketrans("", "", string.punctuation)) (Recommended) |
Fastest (1x baseline C loop) | No (ASCII only; use unicodedata table for Unicode) |
Yes ({c: " " for c in string.punctuation}) |
High-throughput text cleaning, preprocessing pipelines, and stripping exact character sets. |
re.sub(r"[^\w\s]", "", text) |
Moderate (~4x–8x slower) | Yes (matches Unicode punctuation, though keeps _) |
Yes (re.sub(r"[^\w\s]", " ", text)) |
Quick one-off scripts where concise regex syntax matters more than raw throughput (use `r"[^\w\s] |
"".join(c for c in text if c not in punct_set) |
Slowest (~10x–15x slower) | Only if punct_set includes Unicode chars |
Yes (" " if c in punct_set else c) |
Custom per-character predicate logic (e.g., not unicodedata.category(c).startswith("P")) without prebuilding a full Unicode table. |
You must log in or register to comment.
