Skip to content
Related Articles
Open in App
Not now

Related Articles

Python String count() Method

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 23 Feb, 2023
Improve Article
Save Article
Like Article

Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string.

Syntax: 

string.count(substring, start=…, end=…)

Parameters: 

  • The count() function has one compulsory and two optional parameters. 
    • Mandatory parameter: 
      • substring – string whose count is to be found.
    • Optional Parameters: 
      • start (Optional) – starting index within the string where the search starts. 
      • end (Optional) – ending index within the string where the search ends.

Return Value:

count() method returns an integer that denotes number of times a substring occurs in a given string. 

Example 1: Implementation of the count() method without optional parameters

Python3




# Python program to demonstrate the use of
# count() method without optional parameters
 
# string in which occurrence will be checked
string = "geeks for geeks"
 
# counts the number of times substring occurs in
# the given string and returns an integer
print(string.count("geeks"))


Output: 

2

Time Complexity: O(n), where n is the length of the string. This is because we need to traverse the entire string to count the occurrence of the substring.
Auxiliary Space: O(1), as we are not using any extra space in the program, only a string variable is used to store the input string.

Example 2: Implementation of the count() method using optional parameters

Python3




# Python program to demonstrate the use of
# count() method  using optional parameters
 
# string in which occurrence will be checked
string = "geeks for geeks"
 
# counts the number of times substring occurs in
# the given string between index 0 and 5 and returns
# an integer
print(string.count("geeks", 0, 5))
 
print(string.count("geeks", 0, 15))


Output: 

1
2
My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!