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

2024-03-29 04:52:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,计算'a'出现在'Mary had a little lamb'中的次数


Tags: 方法字符串字符次数maryhadlamblittle
3条回答

您可以使用count()

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

正如其他答案所说,使用字符串方法count()可能是最简单的,但是如果您经常这样做,请查看collections.Counter

from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']

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

相关问题 更多 >