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 に答える