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

例如:

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

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


当前回答

String.count (substring),例如:

>>> "abcdabcva".count("ab")
2

这是针对非重叠事件的。 如果你需要计算重叠的次数,你最好检查这里的答案,或者检查下面我的其他答案。

其他回答

根据你的真正意思,我提出以下解决方案:

你的意思是一个空格分隔子字符串的列表,并想知道所有子字符串中的子字符串位置编号是什么: S = 'sub1 sub2 sub3' s.split () .index(“sub2”) > > > 1 你的意思是子字符串在字符串中的char-position: s.find(“sub2”) > > > 5 你的意思是su-bstring的(非重叠)外观计数: s.count(“sub2”) > > > 1 s.count(“子”) > > > 3

使用Python 3.8中引入的赋值操作符,我们可以编写一个简短的函数,在循环中使用str.find()来查找字符串中目标子字符串的重叠实例。已经有一些其他的解决方案使用相同的方法,但这个更短,更快。

赋值表达式不仅用于在last-found实例之后的字符处开始下一个查找操作,还为while循环提供了终端表达式。Str.find()如果没有找到子字符串,则返回-1,在此基础上加上1将得到0,这是false,因此在没有找到更多匹配时退出循环。

# count overlapping occurrences of a substring in a string
def count_overlapping(haystack, needle, start=0, count=0):
    while start := haystack.find(needle, start) + 1:
        count += 1
    return count

print(count_overlapping("moomoooo", "oo"))    # 4

为了进一步优化性能,我们可以查阅草堆。在循环外找到一次,并将其存储在一个局部变量中。这将是更快时,有超过一对夫妇的比赛。

# count overlapping occurrences of a substring in a string
def count_overlapping(haystack, needle, start=0, count=0):
    haystack_find = haystack.find
    while start := haystack_find(needle, start) + 1:
        count += 1
    return count
string="abc"
mainstr="ncnabckjdjkabcxcxccccxcxcabc"
count=0
for i in range(0,len(mainstr)):
    k=0
    while(k<len(string)):
        if(string[k]==mainstr[i+k]):
            k+=1
        else:
            break   
    if(k==len(string)):
        count+=1;   
print(count)

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

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))

目前涉及方法计数的最佳答案并不能真正计算重叠出现的次数,也不关心空子字符串。 例如:

>>> a = 'caatatab'
>>> b = 'ata'
>>> print(a.count(b)) #overlapping
1
>>>print(a.count('')) #empty string
9

如果我们考虑重叠的子字符串,第一个答案应该是2而不是1。 对于第二个答案,如果空子字符串返回0作为asnwer会更好。

下面的代码处理这些事情。

def num_of_patterns(astr,pattern):
    astr, pattern = astr.strip(), pattern.strip()
    if pattern == '': return 0

    ind, count, start_flag = 0,0,0
    while True:
        try:
            if start_flag == 0:
                ind = astr.index(pattern)
                start_flag = 1
            else:
                ind += 1 + astr[ind+1:].index(pattern)
            count += 1
        except:
            break
    return count

现在当我们运行它时:

>>>num_of_patterns('caatatab', 'ata') #overlapping
2
>>>num_of_patterns('caatatab', '') #empty string
0
>>>num_of_patterns('abcdabcva','ab') #normal
2