Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to count occurrences of a word in a string
In this tutorial, we will write a program that counts the number of times a word occurs in a string. You are given a word and a string, and we need to calculate the frequency of the word in the string.
Suppose we have a string "I am a programmer. I am a student." and the word "am". The program will return 2 as the word occurs two times in the string.
Algorithm
1. Initialize the string and the word as two variables. 2. Split the string at spaces using the split() method to get a list of words. 3. Initialize a variable count to zero. 4. Iterate over the list of words. 4.1. Check whether each word in the list equals the given word. 4.2. Increment the count if the two words match. 5. Print the count.
Example
Here's the complete implementation ?
# initializing the string and the word
string = "I am a programmer. I am a student."
word = "am"
# splitting the string at space
words = string.split()
# initializing count variable to 0
count = 0
# iterating over the list
for w in words:
# checking the match of the words
if w == word:
# incrementing count on match
count += 1
# printing the count
print(count)
The output of the above code is ?
2
Using Built-in count() Method
Python strings have a built-in count() method that can directly count word occurrences ?
string = "I am a programmer. I am a student." word = "am" # using count() method on the split list words = string.split() count = words.count(word) print(count)
2
Handling Case Sensitivity
To make the search case-insensitive, convert both the string and word to lowercase ?
string = "I AM a programmer. I am a student." word = "am" # converting to lowercase for case-insensitive matching words = string.lower().split() word = word.lower() count = words.count(word) print(count)
2
Comparison
| Method | Code Length | Best For |
|---|---|---|
| Manual Loop | Longer | Learning and custom logic |
| count() Method | Shorter | Simple word counting |
| Case-insensitive | Medium | Real-world text processing |
Conclusion
Use the manual loop approach to understand the logic, but prefer the built-in count() method for cleaner code. Remember to handle case sensitivity when working with real text data.
