如何更改一个字符串,计算一个字母中有多少个字母来计算一个字母的出现次数?

时间:2013-09-05 13:26:54

标签: python string

我的任务是改变这个:

    sentence = 'The cat sat on the mat.'
    for letter in sentence:
    print(letter)

进入计算小写字母a的出现次数的代码。 我得到了它,但我不知道如何改变它。

3 个答案:

答案 0 :(得分:2)

最好使用count()

>>> sentence = 'The cat sat on the mat.'
>>> sentence.count('a')
3

但是,如果你需要使用循环:

sentence = 'The cat sat on the mat.'
c = 0
for letter in sentence:
    if letter == 'a':
        c += 1
print(c)

答案 1 :(得分:0)

使用正则表达式的另一种方法:

 import re

 sentence = 'The cat sat on the mat.'
 m = re.findall('a', sentence)
 print len(m)

答案 2 :(得分:0)

也许是这样的?

occurrences = {}
sentence = 'The cat sat on the mat.'
for letter in sentence:
    occurrences[letter] = occurrences.get(letter, 0) + 1

print occurrence
相关问题