如何计算给定子字符串在Python字符串中出现的次数?

例如:

>>> 'foo bar foo'.numberOfOccurrences('foo')
2

若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。


当前回答

下面是Python 3中的解决方案,不区分大小写:

s = 'foo bar foo'.upper()
sb = 'foo'.upper()
results = 0
sub_len = len(sb)
for i in range(len(s)):
    if s[i:i+sub_len] == sb:
        results += 1
print(results)

其他回答

带列表理解的一行代码怎么样?从技术上讲,它有93个字符长,不需要PEP-8的纯粹性。正则表达式。Findall答案是最易读的,如果它是一段高级代码。如果您正在构建低级别的东西,并且不想要依赖关系,那么这个方法非常简洁。我给出了重叠的答案。很明显,如果没有重叠的话,使用最高分的答案。

def count_substring(string, sub_string):
    return len([i for i in range(len(string)) if string[i:i+len(sub_string)] == sub_string])

2+其他人已经提供了这个解决方案,我甚至投票了其中一个,但我的可能是新手最容易理解的。

def count_substring(string, sub_string):
    slen = len(string)
    sslen = len(sub_string)
    range_s = slen - sslen + 1
    count = 0
    for i in range(range_s):
        if string[i:i+sslen] == sub_string:
            count += 1
    return count

在给定字符串中查找重叠子字符串的最佳方法是使用正则表达式。使用ahead,它将使用正则表达式库的findall()找到所有重叠的匹配。这里,左边是子字符串,右边是要匹配的字符串。

>>> len(re.findall(r'(?=aa)', 'caaaab'))
3

对于重叠计数,我们可以使用use:

def count_substring(string, sub_string):
    count=0
    beg=0
    while(string.find(sub_string,beg)!=-1) :
        count=count+1
        beg=string.find(sub_string,beg)
        beg=beg+1
    return count

对于非重叠的情况,我们可以使用count()函数:

string.count(sub_string)

这里有一个解决方案,适用于非重叠和重叠的情况。为了澄清:重叠子字符串是指其最后一个字符与其第一个字符相同的子字符串。

def substr_count(st, sub):
    # If a non-overlapping substring then just
    # use the standard string `count` method
    # to count the substring occurences
    if sub[0] != sub[-1]:
        return st.count(sub)

    # Otherwise, create a copy of the source string,
    # and starting from the index of the first occurence
    # of the substring, adjust the source string to start
    # from subsequent occurences of the substring and keep
    # keep count of these occurences
    _st = st[::]
    start = _st.index(sub)
    cnt = 0

    while start is not None:
        cnt += 1
        try:
            _st = _st[start + len(sub) - 1:]
            start = _st.index(sub)
        except (ValueError, IndexError):
            return cnt

    return cnt