Reputation: 527
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
Upvotes: 0
Views: 267
Reputation: 15406
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
Upvotes: 10
Reputation: 54242
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.
Upvotes: 3
Reputation: 85458
You have the same variable name for those character
s (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()
Upvotes: 1