Count number of occurrences of a given substring in a string

后端 未结 30 1681
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
30条回答
  •  醉酒成梦
    2020-11-22 14:33

    #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

提交回复
热议问题