Python Practice › String Programs › Program 44

Count occurrences of a word

EasyString Programs · 44 of 106

Write a Python program to count how many times a whole word occurs in a string.

Advertisement
Input
"food" in "I want to eat fast food"; "are" in "We are learning Python, wow are you"
Output
1
2

Approach

  1. Split into words, strip punctuation, count matches.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment