I\'m trying to find the number of times \'bob\' occurs in a string of characters like \'abdebobdfhbobob\'.
My code (that I found through another stackoverflow question)
If you don't want to use regular expressions you can create all triplets from the string using zip
and then use list.count
:
>>> word = 'bob'
>>> triplets = (''.join(k) for k in zip(*[s[i:] for i in range(len(word))]))
>>> triplets.count(word)
3
The triplets are created by zipping these strings:
▼ ▼ ▼
'abdebobdfhbobob'
'bdebobdfhbobob'
'debobdfhbobob'
▲ ▲ ▲
If you don't mind working with tuples:
>>> word = 'bob'
>>> triplets = zip(*[s[i:] for i in range(len(word))])
>>> triplets.count(tuple(word))
3
Tip: If you're going to count other words as well, use a collections.Counter
.