How to count characters in a string? (python)

我是研究僧i 提交于 2020-01-05 12:10:49

问题


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


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)



回答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



回答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.



来源:https://stackoverflow.com/questions/22724695/how-to-count-characters-in-a-string-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!