---Advertisement---

Python count() Function: How to Use with Examples Best Complete Guide 2025

By Bhavani

Updated On:

---Advertisement---
 Python count() Function

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.


python

string.count(char_or_substring, start, end)

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

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)

pgsql

The count of ‘o’ is 2

The count of ‘o’ using start/end is 1

  • The first example counts all occurrences of ‘o’ in the string.
  • The second example limits the count to the first five characters only.

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)

pgsql

The count of ‘u’ is 3

The count of ‘u’ using start/end is 2

  • The first example counts all ‘u’ characters in the string.
  • The second example counts ‘u’ only within the index range of 6 to 15.

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)

pgsql

The count of ‘to’ is 2

The count of ‘to’ using start/end is 1

  • The first example counts all occurrences of the substring ‘to’.
  • The second example limits the counting to the index range 6 to 15.

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

Python strip() Function

Download Python

Leave a Comment

Index