Possible Duplicate:
Find all occurrences of a substring in Python
I have a string of numbers and am trying to find each time a certain string of numbers occurs in the string.
I know if I use, for example: numString.find(str) that it will tell me the first time it occurs. Is there anyway to modify this statement to find each time that str occurs, not just the first?
Well, is regexp is out of the question, consider this generator code:
We use ‘find’ optional argument of setting the start index of the search, and every time use the last one found, plus the length of the sub-string (so we do’t get the same result every time).
If you want to get overlapping matches, use
+ 1and notlen(substring).You can
'list(find_all('abbccbb', 'bb'))'to get an actual list of indexs.Just a side note: generators (aka, the
yieldkeyword) are more memory efficient than plain lists, and while loops have far less overhead than recursion (and are also much easier to read if you are a human being).