Python program to count the number of a substring in a string
Python program to count the number of a substring in a string
A part of the string is called a substring. This article explains the Python program to find how many numbers of substring are there in the given string (including overlapping cases). There are a few methods discuss below.
Using count function
The count() function is a built-in function in the Python programming language that returns the number of occurrences of a substring that appears in the given string. The following source code uses the count() function to return the number of occurrences of a substring in the string:
# Program to count the number of a substring in the given string #input string String = "TUTORIALANDEXAMPLE" #input substring Substring = "AL" count = String.count(Substring) #Print Count print("The number of occurrences of substring: ", count)
Output
Another method
It is another approach to find the occurrences of a substring in a given string:
#Define string String = "Chitranjan" Substring = "an" count = 0 for i in range(0,len(String)-len(Substring)+1): j=0 b=0 if(String[i]==Substring[j]): k=i while(j<len(Substring)): if(String[k]!=Substring[j]): b=1 break j=j+1 k=k+1 if(b==0): count+=1 #Print Count print("The number of occurrences of substring: ", count)
Output