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.
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
It's as straight forward as the sentence that you speak out loud when talking to someone. Even most keywords are included:
for
each endingin
list of endings:
checkif
ending is present: then stop.
for ending in [".mp3", ".avi"]:
if "test.mp3".endswith(ending):
print(ending)
break
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