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.
Python code
27 linesdef 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
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
- Use re.sub with re.escape for pattern-based highlighting.
- 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
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.