计算字符串中字符的出现次数


计算字符串中字符出现次数的最简单方法是什么?

e.g。计算'a'出现在'Mary有一个小羊羔'的次数

str.count(sub[, start[,
end]])

Return the number of non-overlapping occurrences of substring sub in the
range [start, end]. Optional arguments start and end are interpreted as
in slice notation.

sentence = ‘Mary had a little lamb’
sentence.count(‘a’)
4

您可以使用 count()

>>> 'Mary had a little lamb'.count('a')
4

未经作者同意,本文严禁转载,违者必究!