Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string

Posted by Abie on Stack Overflow See other posts from Stack Overflow or by Abie
Published on 2011-01-16T21:45:34Z Indexed on 2011/01/16 21:53 UTC
Read the original article Hit count: 140

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about string