Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python : Check if string matches a substring in a list, return index of a substring

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading