Count number of occurrences of a given substring in a string

后端 未结 30 1989
不思量自难忘°
不思量自难忘° 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:49

    s = input('enter the main string: ')
    p=input('enter the substring: ')
    l=[]
    for i in range(len(s)):
        l.append(s[i:i+len(p)])
    print(l.count(p))
    

提交回复
热议问题