How can I count the number of times a given substring is present within a string in Python?
For example:
>>> \'foo bar foo\'.numberOfOccurre
One way is to use re.subn. For example, to count the number of occurrences of 'hello' in any mix of cases you can do:
'hello'
import re _, count = re.subn(r'hello', '', astring, flags=re.I) print('Found', count, 'occurrences of "hello"')