[python] 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.

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')

This question is related to python

The answer is


Your return is in your for loop! Be careful with indentation, you want the line return count to be outside the loop. Because the for loop goes through all characters in word, the outer while loop is completely unneeded.

A cleaned-up version:

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

def count_letter(word, char):
    count = 0
    for char in word:
        if char == word:
            count += 1
    return count        #Your return is inside your for loop
r = count_word("banana", "a")
print r

3


x=str(input("insert string"))
c=0
for i in x:
   if 'a' in i:
      c=c+1
print(c)        

"banana".count("ana") returns 1 instead of 2 !

I think the method iterates over the string (or the list) with a step equal to the length of the substring so it doesn't see this kind of stuff.

So if you want a "full count" you have to implement your own counter with the correct loop of step 1

Correct me if I'm wrong...


count_letters=""

number=count_letters.count("")

print number

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter
Counter('banana')

Of course, you can specify one element, e.g.

Counter('banana')['a']

One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.

Also, move the return statement outside the loop; otherwise you will always return after checking the first character.

Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.

Taking these suggestions, your code would look like this:

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

You have a number of problems:

  • There's a problem with your indentation as others already pointed out.
  • There's no need to have nested loops. Just one loop is enough.
  • You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.

This code fixes all these errors:

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

A much more concise way to write this is to use a generator expression:

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

Or just use the built-in method count that does this for you:

print 'abcbac'.count('c')

Alternatively You can use:

mystring = 'banana'
number = mystring.count('a')

I see a few things wrong.

  1. You reuse the identifier char, so that will cause issues.
  2. You're saying if char == word[count] instead of word[some index]
  3. You return after the first iteration of the for loop!

You don't even need the while. If you rename the char param to search,

for char in word:
    if char == search:
        count += 1
return count