Count number of occurrences of a given substring in a string

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

    string.count(substring), like in:

    >>> "abcdabcva".count("ab")
    2
    

    Update:

    As pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping occurrences, you'd better check the answers at: "Python regex find all overlapping matches?", or just check my other answer below.

提交回复
热议问题