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

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


当前回答

要获得所有字母的计数,请使用集合。计数器:

>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4

其他回答

我不知道“最简单的”,但简单的理解可以做到:

>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4

利用内置的和,生成器理解和bool是整数的子类的事实:如何乘字符等于'a'。

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

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()

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

正则表达式非常有用,如果你想要区分大小写(当然还有regex的所有功能)。

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

请注意,regex版本的运行时间大约是它的十倍,只有当my_string非常长或代码处于深度循环中时,这才可能成为问题。

Python 3

有两种方法可以做到这一点:

1)内置函数count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2)不使用函数

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)