How to Validate Text Against Forbidden Words in Python

Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

23 lines
Python 3.9+
def validate_text(text, forbidden_words):
    """
    Checks that text does not contain any forbidden words.
    Returns (is_valid, offending_words) tuple.
    """
    words = text.lower().split()
    found = [word for word in words if word in forbidden_words]
    return len(found) == 0, found


if __name__ == "__main__":
    sample_texts = [
        "The quick brown fox jumps over the lazy dog",
        "This text contains bad words like spam and junk",
        "Clean text without issues here",
    ]
    forbidden = {"spam", "junk", "bad"}

    for idx, text in enumerate(sample_texts, start=1):
        is_valid, found = validate_text(text, forbidden)
        status = "VALID" if is_valid else "INVALID"
        details = f" (found: {found})" if found else ""
        print(f"Text {idx}: {status}{details}")

Output

stdout
Text 1: VALID
Text 2: INVALID (found: ['bad', 'spam', 'junk'])
Text 3: VALID

How it works

This function normalizes the input text to lowercase and splits it into individual words using split(). A list comprehension checks each word against the forbidden set, which allows for O(1) lookups. The function returns a tuple where the first value is True if no forbidden words were found, and the second is the list of offending words (empty when valid). This pattern is simple and readable, making it easy to extend with additional checks like punctuation stripping.

Common mistakes

  • Forgetting to convert the text to lowercase, causing case-sensitive mismatches.
  • Using a list instead of a set for forbidden words, which slows down lookups on large lists.
  • Not handling punctuation properly; 'spam,' would not match 'spam' without additional cleaning.

Variations

  1. Use `any(word in forbidden for word in words)` to only get a boolean result without collecting offending words.
  2. Strip punctuation with `re.findall(r'\b\w+\b', text.lower())` to ignore commas and periods.

Real-world use cases

  • Moderating user-generated comments in a web app by filtering profanity or banned terms.
  • Checking chatbot responses against a list of disallowed topics before sending them to users.
  • Scanning code commit messages for sensitive keywords that should trigger a security review.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.