Python String count()
Method
The count() method in Python is used to count how many times a substring appears in a given string. It is one of the most useful string methods for text analysis and data cleaning.
Syntax
string.count(substring, start, end)
Parameters:
substring
– The string you want to search for (required)start
– The position to start searching (optional)end
– The position to stop searching (optional)
Returns:
- An
integer
value representing the number of times the substring appears within the given range.
Example 1: Basic Usage
text = "apple banana apple orange apple"
print(text.count("apple"))
3
Example 2: With Start and End Parameters
text = "apple banana apple orange apple"
print(text.count("apple", 10, 30))
1
Use Cases
- Finding how often a word appears in a sentence
- Basic data analysis on text fields
- Validating inputs or detecting duplicates
Case Sensitivity
text = "Python python PyThOn"
print(text.count("python"))
1
Note: count()
is case-sensitive. To count in a case-insensitive way, convert the string using lower()
or upper()
first.
Common Mistakes
- Forgetting case sensitivity: "Apple" and "apple" are counted differently.
- Incorrect range: Ensure you use proper start and end index positions.
Interview Tip
count()
is often used in problems like finding duplicates, analyzing text patterns, or simple statistics questions.
Summary
count()
returns how many times a substring appears in the string.- You can specify optional
start
andend
positions. - It is case-sensitive by default.
Practice Problem
Write a program that reads a sentence from the user and prints how many times the word "the" appears (case-insensitive).
sentence = input("Enter a sentence: ")
word_count = sentence.lower().count("the")
print("Count of 'the':", word_count)