我的任务是改变这一点:
sentence = 'The cat sat on the mat.'
for letter in sentence:
print(letter)
变成一个统计小写字母a出现次数的代码。我有点明白,但我不知道如何改变它。
最好使用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)
使用正则表达式的另一种方法:
import re
sentence = 'The cat sat on the mat.'
m = re.findall('a', sentence)
print len(m)
也许是这样的?
occurrences = {}
sentence = 'The cat sat on the mat.'
for letter in sentence:
occurrences[letter] = occurrences.get(letter, 0) + 1
print occurrence