First of all, don't use str
as a variable name, it will mask the built-in name.
As for counting characters in a string, just use the str.count()
method:
>>> s = "Green tree"
>>> s.count("e")
4
If you are just interested in understanding why your current code doesn't work, you are printing 1
four times because you will find four occurrences of 'e', and when an occurrence is found you are printing len(scr)
which is always 1
.
Instead of printing len(scr)
in your if block, you should be incrementing a counter that keeps track of the total number of occurrences found, it looks like you set up a variable a
that you aren't using, so the smallest change to your code to get it to work would be the following (however as noted above, str.count()
is a better approach):
str= "Green tree"
scr= "e"
cstr= len(str)
n=0
a=0
while n < cstr:
if str[n] == scr:
a+=1
n=n+1
print(a)