Skip to content
Advertisement

Letter Count on a string

Python newb here. I m trying to count the number of letter “a”s in a given string. Code is below. It keeps returning 1 instead 3 in string “banana”. Any input appreciated.

JavaScript

Advertisement

Answer

The other answers show what’s wrong with your code. But there’s also a built-in way to do this, if you weren’t just doing this for an exercise:

JavaScript

Danben gave this corrected version:

JavaScript

Here are some other ways to do it, hopefully they will teach you more about Python!

Similar, but shorter for loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:

JavaScript

Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn’t match char and 1 if it does, and then sums them:

JavaScript

The next one filters out all the characters that don’t match char, and counts how many are left:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement