0

我的任务是改变这一点:

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

变成一个统计小写字母a出现次数的代码。我有点明白,但我不知道如何改变它。

4

3 回答 3

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)
于 2013-09-05T13:27:41.513 回答
0

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

 import re

 sentence = 'The cat sat on the mat.'
 m = re.findall('a', sentence)
 print len(m)
于 2013-09-05T13:40:03.040 回答
0

也许是这样的?

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

print occurrence
于 2013-09-05T13:40:39.177 回答