How to count repeated substring in a given string in Python
In this article, we will learn how to use the inbuilt count function using examples. Then we will see how to count repeated substring in a given string in Python.
Python has a built-in function for counting the repeated substring in a given string called count(). As the name suggests, it counts the occurrence of a substring in a given string.
Python – count() function
string="abcdefghijklmnop" string.count(substring, start_index, end_index)
The count function has 3 parameters.
- Substring: This parameter is compulsory since it specifies the string whose occurrence is to be found.
- Start_index: This parameter is optional. It gives the starting index of the string from which the search will begin.
- End_index: This parameter is optional. It gives the ending index of the string where the search for substring will end.
Read: Count number of occurrences of a substring in a string in Python
Count repeated substring in a given string in Python
- This example only contains the compulsory parameter. In this, we first define a string, then by using the count function calculate the occurrence of substring “aab” in the string defined above.
string= "aabbcaabcbbcaabdaab" print(string.count("aab"))
Output:
4
- This example contains compulsory as well as the optional parameters. In this, we first define a string, then by using the count function calculate the occurrence of substring “aab” in the string starting from index 2 and ending at index 15 instead of considering the whole string.
string= "aabbcaabcbbcaabdaab" print(string.count("aab",2,15))
Output:
2
ininini < stirng
ini < sub string
how to solve this