Home > Back-end >  Python : Check if string matches a substring in a list, return index of a substring
Python : Check if string matches a substring in a list, return index of a substring

Time:08-18

I need to detect if a string matches a substring contained in a list, and get the index of the matching substring to assign a value to a variable. Here's the code :

filename = "rec_1.2_LUNCHPLAY_20220616_1645.mp4"
year = '2022'

studio = ['arena', '-1.2', '1.2', '1.3', '1.4', '1.5', '1.8', '1.9', '2bis']
month = [f'{year}01', f'{year}02', f'{year}03', f'{year}04', f'{year}05', f'{year}06']

I'm expecting the output to be [2] and [5].

Any chance someone could help me on that ?

CodePudding user response:

Use enumerate() to iterate over the items in a list and keep track of the current item's position.

for position, substring in enumerate(substrings):
    if substring in message:
        print(position)
        break

But even if you didn't know about enumerate, there is another straightforward solution using range():

for position in range(len(substrings)):
    if substrings[position] in message:
        print(position)
        break

CodePudding user response:

filename = "rec_1.2_LUNCHPLAY_20220616_1645.mp4"
year = '2022'

studio = ['arena', '_1.2', '1.2', '1.3', '1.4', '1.5', '1.8', '1.9', '2bis']
month = [f'{year}01', f'{year}02', f'{year}03', f'{year}04', f'{year}05', f'{year}06']

studio_index = None
month_index = None

for idx, st_match in enumerate(studio):
    if st_match in filename:
        studio_index = idx
        break

for idx, mo_match in enumerate(month):
    if mo_match in filename:
        month_index = idx
        break

print(f'studio index: {studio_index}')
print(f'month index: {month_index}')

Result:

studio index: 2
month index: 5
  • Related