python text.count不返回正确的发生次数

python text.count不返回正确的发生次数,python,text,Python,Text,关于python中的text.count()函数,我有一个问题。 假设我有以下文本,我想返回“CCC”的出现次数: 为什么返回2而不是3?根据str.count方法的文档: >>> help(str.count) Help on method_descriptor: count(...) S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrence

关于python中的text.count()函数,我有一个问题。 假设我有以下文本,我想返回“CCC”的出现次数:


为什么返回2而不是3?

根据
str.count
方法的文档:

>>> help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are interpreted
    as in slice notation.
因此,在您的例子中,
字符串“acccgtgcccc”
中出现了两个不重叠的
CCC


希望有帮助。

最好使用已有的
计数器

from collections import Counter

c = Counter('test')
print (c)
>>> Counter({'t': 2, 'e': 1, 's': 1})
返回子字符串子字符串的出现次数。 在这种情况下:“ACCCGTTGCCCC
给出2,因为子字符串是“CCC”,在字符串中只出现两次。(即,其中“C”彼此相邻至少3次。)

“返回子字符串在[start,end]范围内不重叠的出现次数。”您可能对此感兴趣:谢谢,如果字符串重叠,我应该实现自己的函数还是有一些内置函数?@simalps您可以使用集合中的计数器,它将输出一个频率字典
from collections import Counter

c = Counter('test')
print (c)
>>> Counter({'t': 2, 'e': 1, 's': 1})
Text.count()