How to count the number of a specific letter in a sentence?

One reason your code doesn’t work is because you are comparing char in your function to a constant instead of your input ch. Below are three ways your algorithm can be implemented.

For loop

def count_letters(letter, ch):
    count = 0
    for i in range(len(letter)):
        if letter[i] == ch:
            count += 1
    return count

count_letters('banana', 'a')  # 3


from collections import Counter    
Counter('banana')['a']  # 3

Generator expression

sum(i=='a' for i in 'banana')  # 3

Browse More Popular Posts

Leave a Comment