Check if a Python list item contains a string inside another string

前端 未结 18 2045
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:18

I have a list:

my_list = [\'abc-123\', \'def-456\', \'ghi-789\', \'abc-456\']

and want to search for items that contain the string \'

18条回答
  •  野的像风
    2020-11-22 02:57

    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?

提交回复
热议问题