How to Filter Text to Only Letters, Numbers, and Spaces in Python
A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.
Python code
17 linesdef filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
allowed = set()
if keep_alpha:
allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if keep_digits:
allowed.update("0123456789")
if keep_spaces:
allowed.add(" ")
return "".join(ch for ch in text if ch in allowed)
if __name__ == "__main__":
sample = "Hello, World! 1234. Python is #1 @2024"
filtered = filter_text(sample)
print(f"Original: {sample}")
print(f"Filtered: {filtered}")
print(f"Length: {len(filtered)}")
Output
Original: Hello, World! 1234. Python is #1 @2024
Filtered: Hello World 1234 Python is 1 2024
Length: 33
How it works
This filter_text function builds a set of allowed characters based on three boolean flags, then uses a generator expression with join to keep only characters found in that set. Using sets (allowed.update) makes membership checks fast — O(1) per character — and avoids repeated string scans. The if __name__ == "__main__" guard lets you import the function elsewhere without running the demo. The output removes commas, periods, hashtags, and the @ symbol while preserving the original order and spacing.
Common mistakes
- Confusing keep_spaces with trimming — this function keeps existing spaces but does not collapse multiple spaces.
- Forgetting that punctuation like apostrophes and hyphens are removed, which may break contractions or hyphenated words.
- Mixing up the argument order when calling the function with explicit flags.
Variations
- Use str.isalnum() with a custom loop to keep Unicode letters and digits instead of restricting to ASCII.
- Use regex `re.sub(r'[^a-zA-Z0-9 ]', '', text)` for a more compact one-liner.
Real-world use cases
- Cleaning raw user input from web forms before storing it in a database or search index.
- Preparing text data for NLP pipelines where punctuation and symbols add noise.
- Sanitizing log messages or file names when you need to guarantee only safe characters remain.
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.