Find first matching substring
Eloff
dan.eloff at gmail.com
Fri Jul 17 12:11:18 EDT 2009
Almost every time I've had to do parsing of text over the last 5 years
I've needed this function:
def find_first(s, subs, start=None, end=None):
results = [s.find(sub, start, end) for sub in subs]
results = [r for r in results if r != -1]
if results:
return min(results)
return -1
It finds the first matching substring in the target string, if there
is more than one match, it returns the position of the match that
occurs at the lowest index in the string.
Has anyone else had problems where they could have applied this
function?
It seems to me that python's find (and rfind, index, rindex) could be
modified (the same way that startswith and endswith have been) to
behave this way if a tuple were passed. Do other's agree that this
would be desirable?
Thanks,
Dan
More information about the Python-list
mailing list