Count number of occurrences of a given substring in a string

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

    j = 0
        while i < len(string):
            sub_string_out = string[i:len(sub_string)+j]
            if sub_string == sub_string_out:
                count += 1
            i += 1
            j += 1
        return count
    

提交回复
热议问题