Remove special characters in Python

100% local. Your text never leaves this browser tab.

Strip special characters from a string in Python with one line of regex, or paste your text into the tool below to clean it instantly, no code required. Both keep letters, digits and spaces and drop the rest.

The code

Strip special characters in Python

Use re.sub with a negated character class to keep only what you want:

import re

# Keep only letters, digits and spaces
clean = re.sub(r'[^A-Za-z0-9 ]', '', text)

# Keep word characters only (letters, digits, underscore)
clean = re.sub(r'[^\w]', '', text, flags=re.ASCII)

# Fold accents to ASCII first (café -> cafe), then filter
import unicodedata
ascii_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
clean = re.sub(r'[^A-Za-z0-9 ]', '', ascii_text)

Prefer not to write code? The tool above does the same: it folds accents, then keeps only letters, digits and spaces.

FAQ

Questions, answered plainly

How do I remove special characters from a string in Python?

Use re.sub with a negated character class, like re.sub(r'[^A-Za-z0-9 ]', '', text), which keeps letters, digits and spaces and removes everything else. To also handle accents, normalise with unicodedata first.

How do I keep only alphanumeric characters in Python?

The pattern [^A-Za-z0-9] matches anything that is not a letter or digit, so re.sub(r'[^A-Za-z0-9]', '', text) leaves only alphanumerics. Add a space inside the class to keep spaces too.

Same job in another tool: Python, JavaScript, Excel, Word or SQL.