import itertools
def multis(search,text,start=0):
while start>-1:
f=text.find(search,start)
start=f
if start>-1:
yield f
start+=1
# one based function for nth result only
def nindex(text,search,n):
return itertools.islice(multis(search,text),n-1,n).next()
text = 'abcdefacbdea'
search = 'a'
print("Hit %i: %i" % (3, nindex(text,search,3)))
print ('All hits: %s' % list(multis(search,text)))
Без индексов:
def nthpartition(search,text,n=None):
## nth partition before and after or all if not n
if not n:
n=len(text) # bigger always than maximum number of n
for i in range(n):
before,search,text = text.partition(search)
if not search:
return
yield before,text
text = 'abcdefacbdea'
search = 'a'
print("Searching %r in %r" % (search,text))
for parts in nthpartition(search,text): print(parts)
"""Output:
Searching 'a' in 'abcdefacbdea'
('', 'bcdefacbdea')
('bcdef', 'cbdea')
('cbde', '')
"""