How to Highlight Search Terms in Python Text

Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.

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

Python code

27 lines
Python 3.9+
def highlight_search_term(text: str, term: str) -> str:
    """Highlight all occurrences of term in text using terminal-style markers."""
    if not term:
        return text

    term_lower = term.lower()
    result = []
    i = 0

    while i < len(text):
        # Check if the term starts at position i (case-insensitive)
        if text[i:i + len(term)].lower() == term_lower:
            result.append(f"[{term}]")
            i += len(term)
        else:
            result.append(text[i])
            i += 1

    return "".join(result)


if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog. The fox is quick."
    search_word = "fox"

    highlighted = highlight_search_term(sample_text, search_word)
    print(highlighted)

Output

stdout
The quick brown [fox] jumps over the lazy dog. The [fox] is quick.

How it works

The function scans the text character by character, comparing slices of the same length as the term (case-insensitively). When a match is found, it appends the bracketed term and jumps past it; otherwise, it copies the current character. This avoids replacing inside longer words and handles empty terms gracefully. The result is built with a list and joined for efficiency.

Common mistakes

  • Using regex without escaping special characters like '.' or '*'
  • Matching substrings inside larger words (e.g., 'cat' in 'catalog')
  • Not handling empty search terms, leading to infinite loops

Variations

  1. Use re.sub with re.escape for pattern-based highlighting.
  2. Leverage str.replace with case-insensitive logic (e.g., custom loop or regex).

Real-world use cases

  • Highlighting matched keywords in a search result snippet in a web app.
  • Emphasizing error codes or log identifiers when scanning logs for specific terms.
  • Marking user-specified phrases during document review or text editing tools.

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.