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

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


当前回答

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

其他回答

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

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

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 ,

你可以使用.count():

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

正则表达式?

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

你可以使用循环和字典。

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

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)