i2tutorials

Count() method in Python String Module

Count() method in Python String Module:


count method returns the number of a specified value or word which occurs multiple times in the string. It gives the number of the word or substring which is repeatedly used in the string.


Syntax:

str.count()


Parameters:

It has 3 arguments which are substring, start and end. Here start and end are optional arguments.

  1. Substring: This is used in the string where the count is to be identified.
  2. Start: This index is used at the start of the string from where the count has to be taken
  3. End: This index is used at the end of the string, where the count has to be ended.


Example-1:

Count() method by using only substring.

txt = "I love Switzerland. Switzerland is in Europe. Switzerland is famous for chocolates, Alps mountains are in Switzerland"
x = txt.count ("Switzerland")
print(x)


Output:


Example-2:

Count() method by using substring, start and end arguments.

txt = "I love Switzerland. Switzerland is in Europe. Switzerland is famous for chocolates, Alps mountains are in Switzerland"
x = txt.count("Switzerland",8,78)
print(x)


Output:

Exit mobile version