Itβs easier to understand how to do this:
def count(sub, string): count = 0 for i in xrange(len(string)): if string[i:].startswith(sub): count += 1 return count count('baba', 'abababa baba alibababa') #output: 5
If you like short snippets, you can make it less readable, but smarter:
def count(subs, s): return sum((s[i:].startswith(subs) for i in xrange(len(s))))
This exploits the fact that Python can handle logical integers.
e-satis
source share