Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Letter Count on a string

Tags:

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.

def count_letters(word, char):     count = 0     while count <= len(word):         for char in word:             if char == word[count]:                 count += 1             return count    print count_letters('banana','a') 
like image 645
shaytac Avatar asked May 28 '10 21:05

shaytac


1 Answers

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:

>>> 'banana'.count('a') 3 

Danben gave this corrected version:

def count_letters(word, char):   count = 0   for c in word:     if char == c:       count += 1   return count 

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:

def count_letters(word, char):   count = 0   for c in word:     count += (char == c)   return count 

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:

def count_letters(word, char):   return sum(char == c for c in word) 

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

def count_letters(word, char):   return len([c for c in word if c == char]) 
like image 140
Claudiu Avatar answered Sep 23 '22 03:09

Claudiu