Use bool(re.search(rf"\b{re.escape(word)}\b", text)) from Python’s built-in re module to check for an exact whole word surrounded by word boundaries (\b), or check word in text.split() when words are strictly separated by whitespace—never use plain word in text, which matches partial substrings (e.g., "cat" in "scatter" evaluates to True).

Basic Example

import re

text = "The scatter plot shows a fast cat running."

# 1. Recommended: Regex word boundaries `\b...\b` with `re.escape()`
def contains_exact_word(word: str, sentence: str, ignore_case: bool = False) -> bool:
    flags = re.IGNORECASE if ignore_case else 0
    pattern = rf"\b{re.escape(word)}\b"
    return re.search(pattern, sentence, flags=flags) is not None

print(contains_exact_word("cat", text))             # Output: True
print(contains_exact_word("scatter", text))         # Output: True
print(contains_exact_word("scat", text))            # Output: False (partial substring rejected)
print(contains_exact_word("CAT", text, ignore_case=True))  # Output: True

# 2. Fast whitespace-only check (no punctuation handling):
print("cat" in text.split())                        # Output: True
print("running" in text.split())                    # Output: False ("running." keeps its period!)

Key Details & Edge Cases

  • Always wrap dynamic words in re.escape(word):
    • If the search term contains regex metacharacters like ., +, ?, (, or $ (e.g., "c++", "Dr.", or "item(1)"), unescaped rf"\b{word}\b" either alters matching behavior or raises re.error. Always pass re.escape(word).
  • Why \b fails when the target word starts or ends with non-word characters (like "C++", "@user", or ".env"):
    • Regex \b matches only between a word character (\w: letters, digits, _) and a non-word character (\W or string edge). Because + is \W, r"\bC\+\+\b" fails to match "Learn C++ today" (there is no \b between + and space!).
    • When searching for tokens that may include symbols or hyphens (such as "C++" or "state-of-the-art"), use lookarounds for whitespace/punctuation boundaries instead:
      pattern = rf"(?<!\w){re.escape(token)}(?!\w)"
      print(bool(re.search(pattern, "Learn C++ today!")))  # Output: True
      
  • Underscores _ count as word characters in \b:
    • In Python regex, _ is part of \w, so r"\bfoo\b" will not match "foo_bar" (good for code identifiers), whereas hyphen - is \W, so r"\bfoo\b" will match "foo-bar". Use (?<![A-Za-z0-9_-]) / (?![A-Za-z0-9_-]) if hyphenated compounds must count as single words.
  • Repeated searches on the same text (set(re.findall(r"\w+", text.lower()))):
    • If you need to test hundreds of candidate words against the same document, tokenize the text once into a set (words = set(re.findall(r"\b\w+\b", text.lower()))) so every subsequent word.lower() in words lookup runs in $O(1)$ time.
  • text.split() pitfalls with punctuation and newlines:
    • "Hello, world!".split() produces ['Hello,', 'world!'], so "world" in "Hello, world!".split() returns False due to the trailing !. Use re.search(r"\bworld\b", text) whenever text contains punctuation.

Comparison of Exact-Word Lookup Methods in Python

Method Handles Adjacent Punctuation ("cat.", "(cat)")? Rejects Partial Substrings ("cat" in "scatter")? Handles Symbol Tokens ("C++", "@admin")? Best Used When
re.search(rf"\b{re.escape(w)}\b", text) (Recommended) Yes Yes No (if w starts/ends with \W) General-purpose exact word checks in prose, logs, and natural-language strings.
re.search(rf"(?<!\w){re.escape(w)}(?!\w)", text) Yes Yes Yes (works for "C++", ".env", "#tag") Searching technical terms, hashtags, programming languages, or symbol-prefixed tokens.
w in set(re.findall(r"\b\w+\b", text.lower())) Yes Yes No (alphanumeric/underscore tokens only) Checking hundreds of keywords against the same large string ($O(1)$ per lookup after tokenizing).
w in text.split() No ("cat." != "cat") Yes Yes (if space-delimited) Pre-cleaned, strictly space-delimited token streams with zero punctuation.
w in text (Avoid for whole words) Yes No ("cat" in "scatter" is True) Yes Substring containment checks where partial matches are explicitly desired.