Python Practice › String Programs › Program 44
Count occurrences of a word
Write a Python program to count how many times a whole word occurs in a string.
Input
"food" in "I want to eat fast food"; "are" in "We are learning Python, wow are you"
Output
1 2
Approach
- Split into words, strip punctuation, count matches.
Solution
def count_word(text, word): return sum(1 for w in text.split() if w.strip(",.!?") == word) print(count_word("I want to eat fast food", "food"))print(count_word("We are learning Python, wow are you", "are"))Output
1 2
Line by line
Line 2
Counting whole words avoids matching “are” inside “hare”.
Learn the concept
New to this topic? Read the lesson, then come back.