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

例如:

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

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


当前回答

你可以用两种方法计算频率:

使用str中的count(): a.count (b) 或者,你可以用: len (a.split (b)) 1

其中a是字符串,b是要计算频率的子字符串。

其他回答

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)
def count_substring(string, sub_string):
    inc = 0
    for i in range(0, len(string)):
        slice_object = slice(i,len(sub_string)+i)
        count = len(string[slice_object])
        if(count == len(sub_string)):
            if(sub_string == string[slice_object]):
                inc = inc + 1
    return inc

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

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

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

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

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

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

我不确定这是否已经被研究过了,但我认为这是一个“一次性”单词的解决方案:

for i in xrange(len(word)):
if word[:len(term)] == term:
    count += 1
word = word[1:]

print count

单词是你要搜索的词,术语是你要找的词