2013-09-05 86 views

回答

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) 
0

另一种方法:

import re 

sentence = 'The cat sat on the mat.' 
m = re.findall('a', sentence) 
print len(m) 
0

或许真的喜欢这个?

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

print occurrence 
相关问题