What is the string.count method in Python?
The count method returns the number of occurrences of the substring of a string.
Syntax
string.count(substring, startIndex, endIndex)
Parameters
-
substring: The substring to be searched on the string. -
startIndex: The index from which the substring is to be searched. It is an optional value, and by default the value is0. -
endIndex: The index to which the substring is to be searched. It is an optional value, and by default the value isstring.length.
Return value
The return value is the number of non-overlapping occurrences of the substring in a string.
Example
string = "educative";print("Number of 'e' in the string ", string)print(string.count('e'))string = "iii"print("\nNumber of 'ii' in the string ", string)print(string.count('ii'))string = "educative"print("\nNumber of 'e' in the string ", string, "from index 1 is")print( string.count('e', 1) ) # this will search for 'e' from index 1 to end of the stringstring = "educative"print("\nNumber of 'e' in the string ", string, "between index 1 and 3 is")print( string.count('e', 1, 3) ) # this will search for 'e' from index 1 to 3rd index of the strinf
In the above code, we:
-
Created an
educativestring and used thecountmethod to check how manyeare present in the string. Thecountmethod will return2. -
Created an
iiistring and used thecountmethod to check how manyiiare present in the string. Thecountmethod will return1because in theiiistring, the first twoiicharacters match the substring, so the next search will happen from index2. The search of thesubstringwill take place in a non-overlapping manner. -
Created a string
educativeand checked how manyeare present in the string from the index 1 using thecountmethod. Thecountmethod will return1. -
Created an
educativestring and used thecountmethod to check how manyeare present in the string between the index1and3. Thecountmethod will return0because noeis present between theindex 1 - 3.