Efficient way of testing for substring being one of a set?

tinnews at isbd.co.uk tinnews at isbd.co.uk
Thu Apr 3 07:37:50 EDT 2008


What's the neatest and/or most efficient way of testing if one of a
set of strings (contained in a dictionary, list or similar) is a
sub-string of a given string?

I.e. I have a string delivered into my program and I want to see if
any of a set of strings is a substring of the string I have been
given.  It's quite OK to stop at the first one found.  Ideally the
strings being searched through will be the keys of a dictionary but
this isn't a necessity, they can just be in a list if it could be done
more efficiently using a list.


Is this the best one can do (ignoring the likelihood that I've got
some syntax wrong) :-

    # l is the list
    # str is the incoming string
    answer = ""
    for x in l:
        if str.find(x) < 0:
            continue
        answer = x
        

-- 
Chris Green



More information about the Python-list mailing list