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

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


当前回答

a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
    if str(i) in c:
        count+=1

print(count)

其他回答

正则表达式?

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

正则表达式非常有用,如果你想要区分大小写(当然还有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非常长或代码处于深度循环中时,这才可能成为问题。

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

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

我是pandas库的粉丝,尤其是value_counts()方法。你可以用它来计算字符串中每个字符的出现次数:

>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
     8
a    5
e    4
t    4
o    3
n    3
s    3
d    3
l    3
u    2
i    2
r    2
v    2
`    2
h    2
p    1
b    1
I    1
m    1
(    1
y    1
_    1
)    1
c    1
dtype: int64

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

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