If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that.
Format of the count() method in Python is as follows-
str.count(sub, start, end)
Here sub is the substring which has to be counted in the String str. Parameters start and end are optional, if provided occurrences of substring would be counted with in that range otherwise whole string length is taken as range.
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, where 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-