Saturday, January 2, 2010

Python snippets, find all occurences of string


>>> def find_all(string, occurrence):
...     found = 0
...
...     while True:
...         found = string.find(occurrence, found)
...         if found != -1:
...             yield found
...         else:
...             break
...
...         found += 1
...
>>>
>>> print list(find_all("awpropeoaspwtoapwroawpeoaweo", "p"))
[2, 5, 10, 15, 21]
>>>
>>> print list(find_all("Overllllapping", "ll"))
[4, 5, 6]

Note: Finds all overlapping matches.

No comments: