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

前端 未结 18 1871
-上瘾入骨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:55

    If you only want to check for the presence of abc in any string in the list, you could try

    some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    if any("abc" in s for s in some_list):
        # whatever
    

    If you really want to get all the items containing abc, use

    matching = [s for s in some_list if "abc" in s]
    

提交回复
热议问题