Check if string ends with one of the strings from a list Check if string ends with one of the strings from a list python python

Check if string ends with one of the strings from a list


Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

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


Just use:

if file_name.endswith(tuple(extensions)):


Take an extension from the file and see if it is in the set of extensions:

>>> import os>>> extensions = set(['.mp3','.avi'])>>> file_name = 'test.mp3'>>> extension = os.path.splitext(file_name)[1]>>> extension in extensionsTrue

Using a set because time complexity for lookups in sets is O(1) (docs).


matomo