如何计算字符串中字符出现的次数?

如。“a”在“Mary had a little lamb”中出现了4次。


当前回答

spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

其他回答

“不使用计数查找字符串中需要的字符”方法。

import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

不使用Counter(), count和regex获得所有字符计数的另一种方法

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)
myString.count('a');

更多信息请点击这里

Str.count (a)是计算字符串中单个字符的最佳解决方案。但是如果你需要统计更多的字符,你就必须读取整个字符串的次数,就像你想要统计的字符一样多。

更好的方法是:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

因此,您将有一个dict,它返回字符串中每个字母出现的次数,如果不存在则返回0。

>>>chars['a']
4
>>>chars['x']
0

对于一个不区分大小写的计数器,你可以通过继承defaultdict来覆盖mutator和accessor方法(基类的方法是只读的):

class CICounter(defaultdict):
    def __getitem__(self, k):
        return super().__getitem__(k.lower())

    def __setitem__(self, k, v):
        super().__setitem__(k.lower(), v)


chars = CICounter(int)

for char in text:
    chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0

正则表达式?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))