Python 如何将计算一个句子中有多少个字母的字符串更改为计算一个字母的出现次数?
我的任务是改变这一点:Python 如何将计算一个句子中有多少个字母的字符串更改为计算一个字母的出现次数?,python,string,Python,String,我的任务是改变这一点: sentence = 'The cat sat on the mat.' for letter in sentence: print(letter) 输入一个计算小写字母a出现次数的代码。 我有点明白,但我不知道如何更改它。最好使用count(): 但是,如果需要使用循环,请执行以下操作: sentence = 'The cat sat on the mat.' c = 0 for letter in sentence: if lette
sentence = 'The cat sat on the mat.'
for letter in sentence:
print(letter)
输入一个计算小写字母a出现次数的代码。
我有点明白,但我不知道如何更改它。最好使用
count()
:
但是,如果需要使用循环,请执行以下操作:
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
occurrences = {}
sentence = 'The cat sat on the mat.'
for letter in sentence:
occurrences[letter] = occurrences.get(letter, 0) + 1
print occurrence