This article will tell you how you can best utilize Count Function in Python and follow it up with a detailed programmatic demonstration Following pointers will be covered in this article,
Count Function In Python
Have you ever wondered how to find the number of occurrences of a particular word in a paragraph or a sentence? Well, if your answer is yes. Then you would not have to look any further. Here is a comprehensive illustration of how to use the popular “Count” function in python programming language. Count is an inbuilt function, which helps the user to determine the number of iterations of a certain sub string within a main string. It could be of two types. The first type is without start end parameters and the second type is with parameters.
Moving on with this article on Count Function In Python,
Sample Program For Count Function
Let us look at an example to get a better perspective. The below code takes two inputs from the user. One being the main string and the other being the sub string that is to be counted. The output is the number of times “ROSE” has occurred.
print(“nWelcome to EDUREKA !n”) string1=input(“Enter the stringn”) find=input(“nEnter a word to find its occurrencesn”) print (“The number of occurrences of”, find, “in the sentence **”, string1, “** is =”) print(string1.counts(find)) print(“____________________________”) print(“Thank you have a nice day!”
Output
Count Function Using Optional Parameters
Optional parameters include providing the length of the main string onto to which the search of occurrence in restricted. For example, when we provide the index or the range from 0 to 10. The search on the main string happens only on the first 11 characters. Hence, the term “ROSE” was found only once in that interval. In case, the length of the main string is increased to cover the second “ROSE”. The corresponding output would be two.
print(“nWelcome to EDUREKA !n”) string1=input (“Enter the stringn”) find= input(“nEnter a word to find its occurrencesn ”) print(“The number of occurrences of”, find, “in the sentence **”, string1, “** is =”) print(string1.count(find,0,10)) print (“_______________________”) print (“n Thank You have a nice day!”)
Output
To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.
Got a question for us? Mention them in the comments section of article and we will get back to you.