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

Paul Hankin paul.hankin at gmail.com
Thu Apr 3 07:58:33 EDT 2008


On Apr 3, 12:37 pm, tinn... at isbd.co.uk wrote:
> 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

I'd not use 'l' (confused with '1') or 'str' (a standard module) as
variable names. Your code checks every string in the list even when
it's found one... you can reverse the test and break when the first
one is found. Using 'in' rather than testing the return value of find
is nicer as a substring test. Finally, using the 'else' clause lets
you make it clear that answer is set to the empty string when no match
is found.

for answer in l:
    if str in answer: break
else:
    answer = ''

--
Paul Hankin



More information about the Python-list mailing list