Skip to content

Instantly share code, notes, and snippets.

@fwiffo
Last active January 10, 2022 01:09
Show Gist options
  • Save fwiffo/5233377 to your computer and use it in GitHub Desktop.
Save fwiffo/5233377 to your computer and use it in GitHub Desktop.
Simple implementation of an iterable version of str.find()
def finditer(S, sub, start=0, end=None, overlap=False):
"""Iterate over the indices of substring sub in S.
Returns an iterable, in ascending order, of the indices in S where
substring sub is found such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation. A
True value for the optional argument overlap will allow overlapping
matches.
"""
increment = 1 if overlap else max(1, len(sub))
start = S.find(sub, start, end)
while start != -1:
yield start
start = S.find(sub, start+increment, end)
def rfinditer(S, sub, start=0, end=None, overlap=False):
"""Iterate over descending indices of substring sub in S.
Returns an iterable, in descending order, of the indices in S where
substring sub is found such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation. A
True value for the optional argument overlap will allow overlapping
matches.
"""
if end is None:
end = len(S)
increment = len(sub)-1 if overlap else 0
end = S.rfind(sub, start, end)
while end != -1:
yield end
end = S.rfind(sub, start, end+increment)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment