
Python count() Function: Complete Guide with Examples
Python count() Function: The Python count() function is a built-in method used to count the number of times a specified character or substring appears in a string. It’s useful for string manipulation, data analysis, and text processing.
Syntax of Python count() Function
python
string.count(char_or_substring, start, end)
Python count() Function Parameters:
- char_or_substring (required): The character or substring you want to count in the string.
- start (optional): The starting index for counting. If omitted, it defaults to 0.
- end (optional): The ending index for counting. If omitted, it counts till the end of the string.
Return Value:
- The count() method returns an integer representing the number of occurrences of the specified character or substring.
- If the character or substring is not found, it returns 0.
Examples of count() Function in Python
Example 1: Counting Characters in a String
python
str1 = “Hello World”
str_count1 = str1.count(‘o’)
print(“The count of ‘o’ is”, str_count1)
str_count2 = str1.count(‘o’, 0, 5)
print(“The count of ‘o’ using start/end is”, str_count2)
Output:
pgsql
The count of ‘o’ is 2
The count of ‘o’ using start/end is 1
Explanation:
- The first example counts all occurrences of ‘o’ in the string.
- The second example limits the count to the first five characters only.
Example 2: Counting Characters with start and end Parameters
python
str1 = “Welcome to Software Moji Moji Tutorials!”
str_count1 = str1.count(‘u’)
print(“The count of ‘u’ is”, str_count1)
str_count2 = str1.count(‘u’, 6, 15)
print(“The count of ‘u’ using start/end is”, str_count2)
Output:
pgsql
The count of ‘u’ is 3
The count of ‘u’ using start/end is 2
Explanation:
- The first example counts all ‘u’ characters in the string.
- The second example counts ‘u’ only within the index range of 6 to 15.
Example 3: Counting Substrings in a String
python
str1 = “Welcome to Software Moji Moji – Free Training Tutorials and Videos for IT Courses”
str_count1 = str1.count(‘to’)
print(“The count of ‘to’ is”, str_count1)
str_count2 = str1.count(‘to’, 6, 15)
print(“The count of ‘to’ using start/end is”, str_count2)
Output:
pgsql
The count of ‘to’ is 2
The count of ‘to’ using start/end is 1
Explanation:
- The first example counts all occurrences of the substring ‘to’.
- The second example limits the counting to the index range 6 to 15.
Key Benefits of Using count() in Python
✅ Efficiently counts characters or substrings in a string.
✅ Flexible with start and end parameters for customized counting.
✅ Useful for text analysis, data validation, and word frequency checks.