The Python Oracle

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

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

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands

--

Chapters
00:00 Question
00:31 Accepted answer (Score 604)
00:47 Answer 2 (Score 60)
01:00 Answer 3 (Score 6)
01:18 Answer 4 (Score 6)
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/1835...

Accepted answer links:
[str.endswith]: http://docs.python.org/2/library/stdtype...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #list



ACCEPTED ANSWER

Score 657


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

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



ANSWER 2

Score 67


Just use:

if file_name.endswith(tuple(extensions)):



ANSWER 3

Score 7


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)




ANSWER 4

Score 2


I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.