Count number of occurrences of a given substring in a string

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

    The best way to find overlapping sub-string in a given string is to use the python regular expression it will find all the overlapping matching using the regular expression library. Here is how to do it left is the substring and in right you will provide the string to match

    print len(re.findall('(?=aa)','caaaab'))
    3
    

提交回复
热议问题