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

前端 未结 18 2061
-上瘾入骨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 03:01

    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']
    

提交回复
热议问题