pythonstringlistcompare

Python Get index of a list of substrings when comparing with known string


I have a know string which gets extracted from a WindowsPath and a given list of substrings.

string = ABC1234

The list contains e.g.

list = ['DEF', 'ABC', 'GHI', 'JKL']

I would like to get the index of the string in the list (here: 1) as I need this index for a selction in another list and use its entry.

Thanks very much!!!


Solution

  • You could do something like this:

    s = "ABC123"
    
    for i, val in enumerate(['DEF', 'ABC', 'GHI', 'JKL']):
        if val in s:
           match = i
           break
    else:
        match = None
    

    You could save yourself the second lookup if you did:

    s = "ABC123"
    
    list1 = ['DEF', 'ABC', 'GHI', 'JKL']
    list2 = ['zero', 'one', 'two', 'three']
    
    for key, val in zip(list1, list2):
        if key in s:
            lookup = val
            break
    else:
        lookup = None