How can I count the number of times a given substring is present within a string in Python?

For example:

>>> 'foo bar foo'.numberOfOccurrences('foo')
2

35 Answers
35

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.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *