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

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

Posted by: admin November 1, 2017 Leave a comment

Questions:

What is the pythonic way of writing the following code?

extensions = ['.mp3','.avi']
file_name = 'test.mp3'

for extension in extensions:
    if file_name.endswith(extension):
        #do stuff

I have a vague memory that the explicit declaration of the for loop can be avoided and be written in the if condition. Is this true?

Answers:

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

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

Questions:
Answers:

Just use:

if file_name.endswith(tuple(extensions)):

Questions:
Answers:

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 extensions
True

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

Questions:
Answers:

I have this:

def has_extension(filename, extension):

    ext = "." + extension
    if filename.endswith(ext):
        return True
    else:
        return False