Thursday, February 13, 2020

Python count() method - Counting Substrings

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

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Count Number of Words in a String
  4. Passing Object of The Class as Parameter in Python
  5. raise Statement in Python Exception Handling

You may also like-

  1. Python return Statement With Examples
  2. Global Keyword in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Program to Display Prime Numbers
  5. final Keyword in Java With Examples
  6. Binary Tree Traversal Using Depth First Search Java Program
  7. Spring Profiles With Examples
  8. Input Splits in Hadoop