I'm looking for the simplest way how to iterate over the positions of a substring in a string. Currently I'm using a generator for that, but I have a feeling that it's not quite Pythonian:
def iteratePos(haystack, needle) :
pos = haystack.find(needle)
while pos >= 0 :
yield pos
pos = haystack.find(needle, pos+1)
s = "ABC 11 ABC 111 ABC 1"
for i in iteratePos(s, "ABC") :
print "aye bee see at", i
# finds 0, 7, 15
for i in iteratePos(s, "1") :
print "one at", i
# finds 4, 5, 11, 12, 13, 19
So, is it possible to do this as a reasonable one-liner? Or should I stick to the solution I have?
(Note: Should there be a simple solution for the case when needle is just one character, I'm interested in that as well.)