0

Following this I can find if a string has a certain ending from a list:

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

Is there a way to extend it to find which specific ending it has? e.g, the index of the ending from the list.

Penguin
  • 1,923
  • 3
  • 21
  • 51

3 Answers3

2

For that you need to iterate on the different possible ends,

  • raise a StopIteration if no end matches

    ends = ('.mp3', '.avi')
    first_end = next(end for end in ends if 'test.mp3'.endswith(end))
    print(first_end) # .mp3
    
  • return None if no end matches

    ends = ('.mp4', '.avi')
    first_end = next((end for end in ends if 'test.mp3'.endswith(end)), None)
    print(first_end)  # None
    
azro
  • 53,056
  • 7
  • 34
  • 70
1

It's as straight forward as the sentence that you speak out loud when talking to someone. Even most keywords are included:

for each ending in list of endings: check if ending is present: then stop.

for ending in [".mp3", ".avi"]:
    if "test.mp3".endswith(ending):
        print(ending)
        break
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
0

You can also use list comprehension to parse all possible matches, and then take the first (and the only) match with a ternary if condition operator.

endings = (".mp3", ".avi")
match = [ending for ending in endings if "test.mp3".endswith(ending)]
match = match[0] if match else None
crissal
  • 2,547
  • 7
  • 25