In python, the string count() method is useful for searching and returning the number of times the specified substring exists in the given string.
Following is the pictorial representation of string count() method functionality in python.
If you observe the above diagram, we are trying to search and return how many times the substring “Hi
” exists in the given string “Hi Guest Hi
” using python's count function.
Following is the syntax of defining a string count method in python.
If you observe the above syntax, the count()
method accepts three parameters (string/char
, startIndex
, endIndex
). Here, startIndex
and endIndex
parameters are optional.
0
.Following is the example of the search and return number of times the specified substring/character exists in the given string using the string count()
method in python.
If you observe the above example, we are searching the required substrings to find the number of times the substrings exists in the given string using count()
method without specifying start
/end
index parameters.
When you execute the above python program, you will get the result as shown below.
As discussed in the earlier chapters, python is a case sensitive language due to that for substring 'hi
' we got 0, but for substring 'Hi
' we got 2
. For another substring 'Tutlane
' it returned 1
because the specified substring was found only once in the string.
In the above example, we didn’t mention any start
/end
index positions to search for the specified substrings. By default, the string count()
method will search the complete string for the specified substrings/characters.
If you want to limit the search range, you need to mention the start
and end
index parameter values in the count()
method.
Following is the example of searching and returning the number of times the specified substrings/characters found in the given string using the count()
method.
If you observe the above example, we are limiting the string search by specifying the start
and end
index positions in count()
method.
When you execute the above python program, you will get the result as shown below.
This is how you can use the string count() method in python to search and return the number of times the specified substring/character found in the given string based on your requirements.