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

例如:

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

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


当前回答

下面的逻辑将适用于所有字符串和特殊字符

def cnt_substr(inp_str, sub_str):
    inp_join_str = ''.join(inp_str.split())
    sub_join_str = ''.join(sub_str.split())

    return inp_join_str.count(sub_join_str)

print(cnt_substr("the sky is   $blue and not greenthe sky is   $blue and not green", "the sky"))

其他回答

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

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

带列表理解的一行代码怎么样?从技术上讲,它有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])

对于一个有空格分隔的简单字符串,使用Dict会非常快,请参阅下面的代码

def getStringCount(mnstr:str, sbstr:str='')->int:
    """ Assumes two inputs string giving the string and 
        substring to look for number of occurances 
        Returns the number of occurances of a given string
    """
    x = dict()
    x[sbstr] = 0
    sbstr = sbstr.strip()
    for st in mnstr.split(' '):
        if st not in [sbstr]:
            continue
        try:
            x[st]+=1
        except KeyError:
            x[st] = 1
    return x[sbstr]

s = 'foo bar foo test one two three foo bar'
getStringCount(s,'foo')

我将把我接受的答案作为“简单而明显的方法”,然而,它不包括重叠的情况。 通过多次检查切片就可以简单地找出这些问题——比如:

sum("GCAAAAAGH"[i:].startswith("AAA") for i in range(len("GCAAAAAGH")))

结果是3。

或者可以通过使用正则表达式来实现,如如何使用regex来查找所有重叠的匹配项中所示——它也可以用于良好的代码高尔夫。

这是我的“手工”计数模式重叠出现在一个字符串,它试图不是非常幼稚(至少它不会在每次交互时创建新的字符串对象):

def find_matches_overlapping(text, pattern):
    lpat = len(pattern) - 1
    matches = []
    text = array("u", text)
    pattern = array("u", pattern)
    indexes = {}
    for i in range(len(text) - lpat):
        if text[i] == pattern[0]:
            indexes[i] = -1
        for index, counter in list(indexes.items()):
            counter += 1
            if text[i] == pattern[counter]:
                if counter == lpat:
                    matches.append(index)
                    del indexes[index]
                else:
                    indexes[index] = counter
            else:
                del indexes[index]
    return matches
            
def count_matches(text, pattern):
    return len(find_matches_overlapping(text, pattern))
#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'

counter=0
c=0

for i in range(len(s)-len(p)+1):
    for j in range(len(p)):
        if s[i+j]==p[j]:
            if c<len(p):
                c=c+1
                if c==len(p):
                    counter+=1
                    c=0
                    break
                continue
        else:
            break
print('number of occurences of the substring in the main string is: ',counter)