首页 > 解决方案 > 如何计算python中一个句子中有多少个特定字母?

问题描述

我正在做作业,需要计算字母 a 在句子中出现的次数: The cat sat on the mat

我只使用 python 一年,可以数出那句话中的字母数量,但就我的专业知识而言。

sentence = "The cat sat on the mat"
a = len()
print(a)

我无法计算出需要在变量 a 中添加或更改的内容

标签: python-3.7

解决方案


使用 Python 的string.count()函数,如文档中所示:

string.count(s, sub[, start[, end]])
返回字符串 s[start:end] 中子字符串 sub 的(非重叠)出现次数。开始和结束的默认值以及负值的解释与切片相同。

sentence = 'The cat sat on the mat' 
sentence.count('a')

推荐阅读