Please note that second bab starts where first one ends. This is why using in command isn't giving accurate results.
Asked
Active
Viewed 32 times
2
Zircoz
- 403
- 3
- 12
1 Answers
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
- 19,256
- 7
- 31
- 50
-
`sum(1 for i in range(len(s)-2) if s[i:].startswith('bab')]` – Ignacio Vazquez-Abrams Dec 23 '17 at 13:41