Python文本计数没有返回正确的出现次数

2024-05-18 09:39:03 发布

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

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

text = "ACCCGTTGCCCC"
print text.count("CCC")

为什么它返回2而不是3?你知道吗


Tags: 函数text文本count次数计数printccc
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.

因此在您的例子中,在字符串"ACCCGTTGCCCC"中有两个不重叠的CCC出现。你知道吗

希望有帮助。你知道吗

Text.count() 

返回子字符串的出现次数。 在这种情况下:“ACCCGTTGCCCC” 给你2,因为你的子串是“CCC”的集合,它在字符串中只出现了两次(也就是说,其中“C”彼此相邻放置了至少3次)

最好是使用已经可用的Counter。你知道吗

from collections import Counter

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

相关问题 更多 >