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

如。“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'。

其他回答

a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print(key, a.count(key))

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

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

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)

要查找句子中字符的出现情况,您可以使用下面的代码

首先,我从句子中取出了唯一的字符,然后我计算了每个字符在句子中的出现次数,其中包括空格的出现次数。

ab = set("Mary had a little lamb")

test_str = "Mary had a little lamb"

for i in ab:
  counter = test_str.count(i)
  if i == ' ':
    i = 'Space'
  print(counter, i)

以上代码的输出如下所示。

1 : r ,
1 : h ,
1 : e ,
1 : M ,
4 : a ,
1 : b ,
1 : d ,
2 : t ,
3 : l ,
1 : i ,
4 : Space ,
1 : y ,
1 : m ,

使用数:

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