Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Sunday, January 19, 2020

Python program to count the number of occurrences of a letter in a word or in a sentence

         Suppose if we want to count the number of occurrences of a letter in a word or in a sentence, we can use the count function from python.



This is the sample code. I am assigning a string to the variable called text. Then i am counting the number of 'e' in the text.



This code produces an output of 8.

Python String count() 

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

 It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

 The syntax of count() method is: 

string.count(substring, start=..., end=...)
By providing the start value the function searches for the substring only after the start index.

If an end value is given the function searches until the end of this index.

Example

In this example there is a list consisting of different words. I will print only the words that match my condition. 

condition: Print all the words that has 4 'r' in it.





The above program will print 'strringrr', 'strarirngr' as they have 4 'r' in them.

#python #count #lettercount

1 comment:

  1. Wow, your post is very helpful. I have learned a lot from this post. Check out this link to learn more and more: https://sisayed360.blogspot.com/

    ReplyDelete