我的任务就是要改变这样的:如何更改一个字符串来统计一个字母的出现次数中的多少个字母?
sentence = 'The cat sat on the mat.'
for letter in sentence:
print(letter)
成计数小写字母一个出现的编号。 我有种得到它,但我不知道如何改变它。
我的任务就是要改变这样的:如何更改一个字符串来统计一个字母的出现次数中的多少个字母?
sentence = 'The cat sat on the mat.'
for letter in sentence:
print(letter)
成计数小写字母一个出现的编号。 我有种得到它,但我不知道如何改变它。
这是更好地使用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