0

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
5
  • 2
    Yep, character == character is going to be very true all the time. Commented Aug 25, 2010 at 0:37
  • Avoid using standard library names (string) or builtins as variable names. Commented Aug 25, 2010 at 1:02
  • Theres a new "Counter" object in python 2.7 collections that contains some useful methods for common count manipulations, like "most_common(n)". docs.python.org/library/… Commented Aug 25, 2010 at 1:14
  • @Greg Hewgill, except for NaN! float('nan') == float('nan') == False Commented Aug 25, 2010 at 1:42
  • @carl: ...and for objects where you've redefined __eq__ to do something else. :) Commented Aug 25, 2010 at 1:45

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

What about x = reduce(operator.add, (char == 'e' for char in "Do reinvent the wheel"))?
sum(char == 'e' for char in "Reinvent the wheel another way") == 6. Much nicer than reduce and operator.add.
3
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.

Comments

1

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

2 Comments

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 >>>
never mind, stupid comment. I had to add the quote marks. Thanks so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.