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

tinnews at isbd.co.uk tinnews at isbd.co.uk
Thu Apr 3 08:11:51 EDT 2008


Paul Hankin <paul.hankin at gmail.com> wrote:
> 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.

Neither would I, it was just thrown together to show how I was
thinking.

>                 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 = ''
> 
OK, that does improve things somewhat, thanks.

-- 
Chris Green



More information about the Python-list mailing list