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

前端 未结 18 1841
-上瘾入骨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]
    
    0 讨论(0)
  • 2020-11-22 02:55

    Use the __contains__() method of Pythons string class.:

    a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    for i in a:
        if i.__contains__("abc") :
            print(i, " is containing")
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-11-22 03:00
    my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    
    for item in my_list:
        if (item.find('abc')) != -1:
            print ('Found at ', item)
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-11-22 03:01
    mylist=['abc','def','ghi','abc']
    
    pattern=re.compile(r'abc') 
    
    pattern.findall(mylist)
    
    0 讨论(0)
提交回复
热议问题