Penguin
Penguin

Reputation: 2441

Check which ending a string has from a list

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.

Upvotes: 0

Views: 65

Answers (3)

crissal
crissal

Reputation: 2647

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

Upvotes: 0

Thomas Weller
Thomas Weller

Reputation: 59513

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

Upvotes: 1

azro
azro

Reputation: 54168

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
    

Upvotes: 2

Related Questions