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

例如:

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

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


当前回答

import re
d = [m.start() for m in re.finditer(pattern, string)] 
print(d)

这将查找子字符串在字符串中被找到的次数并显示索引。

其他回答

场景1:句子中出现一个单词。 str1 =“这是一个例子,很简单”。单词“is”的出现。让str2 = "is"

count = str1.count(str2)

场景二:句子中出现句式。

string = "ABCDCDC"
substring = "CDC"

def count_substring(string,sub_string):
    len1 = len(string)
    len2 = len(sub_string)
    j =0
    counter = 0
    while(j < len1):
        if(string[j] == sub_string[0]):
            if(string[j:j+len2] == sub_string):
                counter += 1
        j += 1

    return counter

谢谢!

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

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

在Python 3中,要查找字符串中子字符串的重叠情况,该算法将执行以下操作:

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

我亲自检查了这个算法,它是有效的。

如果你想数整个字符串,这是可行的。

stri_count="If you're looking to count the whole string this can works"
print(len(stri_count))

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