Master Python’s str.count(): How to Count Characters & Substrings with Examples
Master Python’s str.count(): How to Count Characters & Substrings with Examples
The str.count() method is a lightweight, built‑in tool that returns how many times a specified substring appears in a string. Whether you need to tally single characters, multi‑character patterns, or count within a specific slice of the text, str.count() handles it all with speed and precision.
Why Use str.count()?
- Simple, O(n) time complexity for most cases.
- Zero‑dependency: no external libraries required.
- Ideal for preprocessing, data validation, or quick analytics on text.
Syntax Overview
string.count(sub[, start[, end]])
Parameters
sub– The substring or single character you want to count.start(optional) – Index to begin the search. Defaults to0.end(optional) – Index to stop the search (non‑inclusive). Defaults to the string’s length.
Return Value
The method returns an integer indicating the number of non‑overlapping occurrences of sub between the optional start and end indices. If sub isn’t found, it returns 0.
Practical Examples
Example 1: Counting a Single Character
str1 = "Hello World"
print("Count of 'o':", str1.count('o'))
print("Count of 'o' between indices 0 and 5:", str1.count('o', 0, 5))
Output:
Count of 'o': 2 Count of 'o' between indices 0 and 5: 1
Example 2: Counting a Character Across a Phrase
str1 = "Welcome to Guru99 Tutorials!"
print("Count of 'u':", str1.count('u'))
print("Count of 'u' between indices 6 and 15:", str1.count('u', 6, 15))
Output:
Count of 'u': 3 Count of 'u' between indices 6 and 15: 2
Example 3: Counting a Substring in a Longer Text
str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
print("Count of 'to':", str1.count('to'))
print("Count of 'to' between indices 6 and 15:", str1.count('to', 6, 15))
Output:
Count of 'to': 2 Count of 'to' between indices 6 and 15: 1
Key Takeaways
str.count()returns an integer count of non‑overlapping occurrences.- Optional
startandendarguments let you limit the search to a specific slice. - It’s perfect for quick text analytics, data cleaning, or feature extraction in Python scripts.
Python
- Python Print() Function: A Practical Guide with Examples
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Master Python `format()` Strings with Clear Examples
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- Master Python Lambda Functions: Practical Examples & Best Practices
- Python round() Function Explained with Practical Examples
- Mastering Python's map() Function: Syntax, Examples, and Best Practices
- Python timeit() – Measuring Execution Time with Practical Examples
- Python list.count(): Expert Guide with Practical Examples
- Python Module Importing – A Practical Guide with Examples