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)):
There is two ways: regular expressions and string (str) methods.
String methods are usually faster ( ~2x ).
import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)
792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)
274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)