Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count characters in a string? (python)

Tags:

python

count

# -*- 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?

like image 808
Attila Avatar asked Nov 24 '25 19:11

Attila


1 Answers

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)
like image 155
Andrew Clark Avatar answered Nov 26 '25 11:11

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!