How to Filter Toxic Keywords in Python

Filter toxic keywords from text by replacing each occurrence with asterisks, useful as a basic guardrail for LLM inputs.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 12 views 0 copies

Python code

23 lines
Python 3.9+
TOXIC_KEYWORDS = ["insult", "threat", "hate", "violence", "spam"]


def guardrails_filter(text: str, keywords: list[str] | None = None) -> str:
    """Filter out toxic keywords from the given text.

    Args:
        text: The input text to filter.
        keywords: Optional keyword list. Defaults to TOXIC_KEYWORDS.

    Returns:
        The filtered text with toxic keywords replaced by '*' characters.
    """
    keywords = keywords or TOXIC_KEYWORDS
    filtered_text = text
    for keyword in keywords:
        filtered_text = filtered_text.replace(keyword, "*" * len(keyword))
    return filtered_text


if __name__ == "__main__":
    sample_text = "This is a hate message and a threat to violence."
    print(guardrails_filter(sample_text))

Output

stdout
This is a **** message and a ****** to ********.

How it works

The function iterates through a list of keywords and uses str.replace() to substitute each toxic word with asterisks of the same length. The optional keywords parameter defaults to a predefined list, letting you reuse the filter with custom lists. Because replace() handles substring matches, this approach works for any text where toxic terms appear as standalone or embedded words.

Common mistakes

  • Replacing keywords with fixed-length asterisks instead of matching keyword length
  • Forgetting that substring matching may filter non-toxic words containing the keyword
  • Not handling case sensitivity — 'Hate' won't be caught by 'hate'

Variations

  1. Use regex with word boundaries to avoid partial-word matches
  2. Convert text and keywords to lowercase before filtering for case-insensitive matching

Real-world use cases

  • Pre-processing user prompts before sending to an LLM API to block harmful or spammy content.
  • Sanitizing chat messages in a moderation queue to strip offensive terms before display.
  • Redacting sensitive or banned words in logs or analytics pipelines before storage.

Sponsored

Run this sample

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

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.