Let's say I got the string a = "bob"
and b = "bobob"
when I perform a in b
, how can I count that bob
appears twice in b
?
Let's say I got the string a = "bob"
and b = "bobob"
when I perform a in b
, how can I count that bob
appears twice in b
?
You can use a generator expression that iterates through a rolling window of b
over the difference in lengths between a
and b
and tests if the slice of b
in that window is equal to a
:
sum(b[i: i + len(a)] == a for i in range(len(b) - len(a) + 1))
This returns: 2