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

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


当前回答

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

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

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

其他回答

使用数:

sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4

正则表达式?

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

Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print(key, a.count(key))

这个简单直接的函数可能会有帮助:

def check_freq(x):
    freq = {}
    for c in set(x):
       freq[c] = x.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}

如果需要理解:

def check_freq(x):
    return {c: x.count(c) for c in set(x)}