提问者:小点点

在Python中使用count()计算子字符串的数量


这是我的字符串'caaasb'。 我知道子字符串'aa'出现的次数是两次:

  1. “caaasb”

但是当我用Python编写下面的代码时,它返回一个值1

'caaasb'.count('aa')
> 1

我的理解错在哪里?


共3个答案

匿名用户

您可以在此处使用re.findall技巧:

inp = "caaasb"
num_matches = len(re.findall(r'a(?=a)', inp))
print "There were " + str(num_matches) + " aa matches in the input"

这将打印:

There were 2 aa matches in the input

上面使用的技巧是通过在每次匹配中只实际消耗第一个aa来匹配aa。 每次匹配中的第二个a使用正向前瞻断言。 这就绕开了消耗/重复计算的问题。

匿名用户

下面是一个在没有re的情况下实现的解决方案:

def get_overlapping_count(string: str, sub_string: str) -> int:
    count = 0
    start_index = 0

    while True:
        start_index = string.find(sub_string, start_index) + 1

        if start_index <= 0:
            return count

        count += 1

get_overlaping_count(“caaasb”,“aa”)返回2

匿名用户

列表理解的方式:

def custom_count(s, sub):
    return len([i for i in range(len(s) - len(sub) + 1) if s[i:i + len(sub)] == sub])

print(custom_count('caaasb', 'aa'))

函数中的列表包含子字符串的所有索引。len将返回计数。