How to check if a string is a substring of items in a list of strings
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 How To Check If A String Is A Substring Of Items In A List Of Strings
00:25 Accepted Answer Score 1372
00:45 Answer 2 Score 107
00:59 Answer 3 Score 20
01:46 Answer 4 Score 238
02:02 Thank you
--
Full question
https://stackoverflow.com/questions/4843...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #list
#avk47
ACCEPTED ANSWER
Score 1372
To check for the presence of 'abc' in any string in the list:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in xs):
    ...
To get all the items containing 'abc':
matching = [s for s in xs if "abc" in s]
ANSWER 2
Score 238
Just throwing this out there: if you happen to need to match against more than one string, for example abc and def, you can combine two comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
Output:
['abc-123', 'def-456', 'abc-456']
ANSWER 3
Score 107
Use filter to get all the elements that have 'abc':
>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list(filter(lambda x: 'abc' in x, xs))
['abc-123', 'abc-456']
One can also use a list comprehension:
>>> [x for x in xs if 'abc' in x]
ANSWER 4
Score 20
This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the non-iterable items, use the following:
[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]
then, with such a list:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
you will still get the matching items (['abc-123', 'abc-456'])
The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?