2

Please note that second bab starts where first one ends. This is why using in command isn't giving accurate results.

Zircoz
  • 504
  • 3
  • 14

1 Answers1

2

You could use a regex. I think what you want is a positive lookahead. This basically means that you can search for overlapping occurrences of a pattern (bab).

So, I created a regex101 for the expression that will work for this.

And implemented in Python:

import re
s = 'arbabababtybab'
o = re.findall('(?=(bab))', s)
n = len(o)

which gives o (the occurrences) as a list of: ['bab', 'bab', 'bab', 'bab'] and n as the number of them (the count): 4.


Alternatively, you could use string slicing to do this with a list-comprehension:

s = 'arbabababtybab'
o = [s[i:i+3] for i in range(len(s)-2) if s[i:i+3] == 'bab']
n = len(o)

which gives the same results as above.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54