tags:

views:

72

answers:

3

want to count the number of times a letter appears in a string, having issues here. any help

def countLetters(string, character):
    count = 0
    for character in string:
        if character == character:
            count = count + 1
    print count
+1  A: 

You have the same variable name for those characters (which means they'll always be equal). Try:

def countLetters(string, character):
    count = 0
    for char in string:
        if char == character:
            count = count + 1
    print count

Of course this is the same as str.count()

NullUserException
Thanks, this seems correct but I'm getting this error in IDLE>>> countLetters(california, a)Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> countLetters(california, a)NameError: name 'california' is not defined>>>
mike varela
never mind, stupid comment. I had to add the quote marks.Thanks so much
mike varela
+3  A: 
if character == character:

character will always equal character because they're the same variable. Just change the names of those variables. Maybe search_character?

I also wouldn't use string as a variable name since it's the name of a built-in module.

Brendan Long
+9  A: 

The others have covered the errors of your function. Here's an alternative way of doing what you want. Python's built-in string method count() returns the number of occurrences of a string.

x = "Don't reinvent the wheel."
x.count("e")

Gives:

5
Dominic Bou-Samra
+1 - Pythonic, dude.
duffymo
What about `x = reduce(operator.add, (char == 'e' for char in "Do reinvent the wheel"))`?
Brendan Long
Reduce is very unpythonic. It's best to avoid map/reduce in Python if possible.
Dominic Bou-Samra