Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of substrings in list of strings

I'd like to find if a list of substrings is contained in a list. For example, I have:

    string_list = ['item1', 'item2', 'subject3', 'subject4']

and list of substrings

    substrings = ['item', 'subject']

I'd like to find if 'item' or 'subject' are included in any item of string_list. Individually, I would do something like:

    any('item' in x for x in string_list)

This works for one substring but I would like to find a pretty way of searching for both strings in the list of substrings.

like image 940
Jonathan C Lee Avatar asked Aug 28 '17 20:08

Jonathan C Lee


2 Answers

any(y in x for x in string_list for y in substrings)
like image 98
Roman Pekar Avatar answered Sep 22 '22 10:09

Roman Pekar


Since the substrings are actually at the start, you can use str.startswith which can take a tuple of prefixes:

any(x.startswith(('item', 'subject')) for x in string_list)
like image 40
Moses Koledoye Avatar answered Sep 23 '22 10:09

Moses Koledoye