How To Count Characters In A String? (python)
Solution 1:
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)
Solution 2:
Use the count method:
>>> st="Green tree"
>>> st.count('e')
4
If the count method is broken on your Python ;-), you can use a for loop:
st="Green tree"
tgt='e'
i=0
for c in st:
if c==tgt: i+=1
print i
# 4
If you really want a while loop:
idx=0
i=0
while idx<len(st):
if st[idx]==tgt: i+=1
idx+=1
print i
But, this being Python, a more 'Pythonic' approach if your count method broken is to use sum
on a generator expression:
>>> sum(1 for c in st if c=='e')
4
Solution 3:
scr= "e"
##
print(len(scr))
For why it's doing this, it's doing what you asked, and printing the length of the variable scr
, which is always one.
You're best to use the str.count()
method as others mentioned, or increment a counter yourself manually.
Post a Comment for "How To Count Characters In A String? (python)"