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

例如:

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

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


当前回答

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

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

其他回答

def count_substring(string, sub_string):
    k=len(string)
    m=len(sub_string)
    i=0
    l=0
    count=0
    while l<k:
        if string[l:l+m]==sub_string:
            count=count+1
        l=l+1
    return count

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(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)

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

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

这个问题不是很清楚,但我可以回答你表面上的问题。

一个长度为L个字符的字符串S,其中S[1]是字符串的第一个字符,S[L]是最后一个字符,它有以下子字符串:

空字符串”。这里有一个。 对于从1到L的每一个值A,对于从A到L的每一个值B,字符串S[A]..S[B] (包容)。有L + L-1 + L-2 +…1个字符串,对于a 共0.5*L*(L+1)。 注意,第二项包括S[1]..S[L], 即整个原始字符串S。

所以,在长度为L的字符串中有0.5*L*(L+1) +1个子字符串,在Python中呈现这个表达式,你就有了字符串中出现的子字符串的数量。

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

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)