Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string
- by Abie
The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python.
The code that I wrote:
def countLetters(str, ch):
count=0
index=0
for ch in str:
if ch==str[index]:
count=count+1
index=index+1
print count
when I use this function, it measures the length of the string instead of how many times the character occurs in the string. What did I do wrong? What is the right way to write this code?