How to check if any item from a list of strings is in a big string?

Chris Rebert clp2 at rebertia.com
Thu Jul 9 21:43:31 EDT 2009


On Thu, Jul 9, 2009 at 6:36 PM, inkhorn<matt.dubins at sympatico.ca> wrote:
> Hi all,
>
> For one of my projects, I came across the need to check if one of many
> items from a list of strings could be found in a long string.  I came
> up with a pretty quick helper function to check this, but I just want
> to find out if there's something a little more elegant than what I've
> cooked up.  The helper function follows:
>
> def list_items_in_string(list_items, string):
>    for item in list_items:
>        if item in string:
>            return True
>    return False
>
> So if you define a list x = ['Blah','Yadda','Hoohoo'] and a string y =
> 'Yip yip yippee Blah' and you run list_items_in_string(x, y), it
> should return True.
>
> Any ideas how to make that function look nicer? :)

any(substr in y for substr in x)

Note that any() was added in Python 2.5

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list