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 ?
>Solution :
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