If you want to count the number of occurrences of a specific substring in a string in Python, the most efficient way is to use the built-in count() method.
The general syntax of the Python count() method is as follows-
str.count(sub, start, end)
Parameters:
- sub- The substring you want to count in the String str.
- start (optional)- The starting index of the search range.
- end (optional)- The ending index of the search range.
If start and end are not provided, Python counts occurrences across the entire string. When they are specified, only the substring occurrences within that slice are counted.
Python string count() method example
1. Using count() method with no start and end parameters.
s = "This a test string to test count method"
print('Count-', s.count("test"))
Output
Count- 2
2. Using count() method with start and end parameters.
s = "This a test string to test count method"
# passing range for search
count = s.count("test", s.find("test"), s.rfind("test"))
print('Count-', count)
Output
Count- 1
In the example range for search is passed using find() and rfind() methods, find() returns the lowest index in the string where substring is found and rfind() returns the highest index in the string where substring sub is found.
3. Calculating count of character ‘o’ in the String.
s = "This a test string to test count method"
count = s.count("o")
print('Count-', count)
Output
Count- 3
That's all for this topic Python count() method - Counting Substrings. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-