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.

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

Python code

17 lines
Python 3.9+
def 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

stdout
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

  1. Use str.isalnum() with a custom loop to keep Unicode letters and digits instead of restricting to ASCII.
  2. 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

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.