简体   繁体   English

如何计算字符串中的字符? (蟒蛇)

[英]How to count characters in a string? (python)

# -*- 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 我必须在-str-字符串中计算“ e”,但是当我运行此脚本时,我得到了

1
1
1
1

instead of 4. 而不是4。

What's the problem? 有什么问题?

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: 如果count方法在您的Python ;-)上损坏,则可以使用for循环:

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: 如果您真的想要一个while循环:

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: 但是,这是Python,如果您的count方法损坏了,则在生成器表达式上使用sum ,这是一种更“ Pythonic”的方法:

>>> sum(1 for c in st if c=='e')
4

First of all, don't use str as a variable name, it will mask the built-in name. 首先,不要将str用作变量名,它会掩盖内置名称。

As for counting characters in a string, just use the str.count() method: 至于计数字符串中的字符,只需使用str.count()方法:

>>> 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 . 如果您只是想了解为什么当前代码不起作用,您将打印1次四次,因为您会发现四个出现的'e',并且当找到一个出现时,您正在打印len(scr)始终为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): 而不是在if块中打印len(scr) ,您应该增加一个计数器来跟踪找到的总发生次数,这看起来像是设置了一个未使用的变量a ,因此对您的代码如下所述(但是如上所述, str.count()是一种更好的方法):

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)
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. 对于为什么它这样做,它在做什么,你问什么,并打印变量的长度scr ,这始终是一个。

You're best to use the str.count() method as others mentioned, or increment a counter yourself manually. 最好像其他提到的那样使用str.count()方法,或者自己手动增加计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM