Count number of occurrences of a given substring in a string

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

    If you want to find out the count of substring inside any string; please use below code. The code is easy to understand that's why i skipped the comments. :)

    string=raw_input()
    sub_string=raw_input()
    start=0
    answer=0
    length=len(string)
    index=string.find(sub_string,start,length)
    while index<>-1:
        start=index+1
        answer=answer+1
        index=string.find(sub_string,start,length)
    print answer
    

提交回复
热议问题