私の仕事はこれを変更することです:
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