如何计算字符串中的字符? (蟒蛇) [英] How to count characters in a string? (python)

查看:53
本文介绍了如何计算字符串中的字符? (蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我必须在-str-字符串中计算 e,但是运行此脚本时,我会得到

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

1
1
1
1

而不是4。

出什么问题了?

推荐答案

首先,不要使用 str 作为变量名,它将掩盖内置名称。

First of all, don't use str as a variable name, it will mask the built-in name.

关于计数字符串中的字符,只需使用 str.count() 方法:

As for counting characters in a string, just use the str.count() method:

>>> s = "Green tree"
>>> s.count("e")
4

如果您只是想了解为什么您当前的代码不起作用,您正在打印 1 四次,因为您会发现四个出现的'e',并且当找到一个出现时,您正在打印 len(scr)始终为 1

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.

代替打印 len(scr)在您的if块中,您应该增加一个计数器来跟踪找到的总发生次数,就像您设置了一个变量 a 您未使用的代码,因此为了使代码正常工作,对代码进行的最小更改如下(但是如上所述, str.count( )是一种更好的方法):

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)

这篇关于如何计算字符串中的字符? (蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆