Count a Word, Not Its Substrings

Medium ⏱ 12 min 46% acceptance ★★★★★ 4.7
Naive text.count('cat') also counts 'catalog'. Write count_word(text, word) counting only whole-word, case-insensitive occurrences using \b boundaries and re.IGNORECASE — and escape the word with re.escape in case it carries regex metacharacters.

Examples

Example 1
Input
count_word('Cat catalog CAT scatter', 'cat')
Output
2
Explanation

Only the standalone 'Cat' and 'CAT' count.

Constraints

  • Case-insensitive.
  • Use re.escape on the word.

Topics

Regular Expressionsword boundaries

Companies

GrammarlyGoogleCoursera

Hints

Hint 1

rf'\b{re.escape(word)}\b'.

Hint 2

len(re.findall(...)) counts.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.