Home » Python

Counting the occurrences of a substring in a string using string.count() in Python

Python string.count() function with example: In this article, we are going to learn with an example about string.count() function, to count occurrences of a substring in string.
Submitted by IncludeHelp, on January 19, 2018

Python - string.count() function

string.count() is an in-built function in Python, it is used to find the occurrences of a substring in a given string. It returns an integer value which is the occurrences of the substring.

Syntax:

string.count(substring, [start_index], [end_index])

Here,

  • substring is a part of string whose occurrences is to be found.
  • [start_index] is an optional argument; it will be the start index of the string, where search will start.
  • [end_index] is an optional argument; it will be the end index of the string, where search will stop.

Return value: function returns total number of occurrences of substring.

Example:

    Input string is: "I live in India, India is a great country"
    Substring to find : "India"
    Start_index: None
    End_index: None
    Output: 2   

    Input string is: "I live in India, India is a great country"
    Substring to find : "India"
    Start_index: 0
    End_index: 15
    Output: 1   

Source code:

#Python code to find occurrences 
#of a substring in a string 

#defining a string
str = "I live in India, India is a great country"

#finding occurrences of 'India'
#in complete string
print(str.count("India"))

#finding occurrences of 'India'
#from 0 to 15 index
print(str.count("India",0,15))

#finding occurrences of 'i' (small 'i')
#in complete string
print(str.count("i"))

Output

    2
    1
    5





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.