Python String | count()

count() function in 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:
1)substring – string whose count is to be found.

Optional Parameters:
1)start (Optional) – starting index within the string where search starts.
2)end (Optional) – ending index within the string where search ends.

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

Below is the Python implementation of the count() method without optional parameters:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"))

chevron_right


Output:

2

Below is the Python implementation of the count() method using optional parameters.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

1
2


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet, shubham_singh



Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.