3
# -*- coding:UTF-8 -*-

str= "Green tree"
scr= "e"

cstr= len(str)
n=0
a=0

while n < cstr:
    if str[n] == scr:
        print(len(scr))
    n=n+1

I have to count "e" in -str- string, but when I run this script I get

1
1
1
1

instead of 4.

What's the problem?

1
  • 5
    Don't use str as a variable name. It shadows the builtin. Commented Mar 28, 2014 at 23:08

3 Answers 3

6

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.