Use endswith with multiple extensions

PythonListFile

Python Problem Overview


I'm trying to detect files with a list of extensions.

ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv"]
if file.endswith(ext): # how to use the list ?
   command 1
elif file.endswith(""): # it should be a folder
   command 2
elif file.endswith(".other"): # not a video, not a folder
   command 3

Python Solutions


Solution 1 - Python

Use a tuple for it.

>>> ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv"]

>>> ".wmv".endswith(tuple(ext))
True
>>> ".rand".endswith(tuple(ext))
False

Instead of converting everytime, just convert it to tuple once.

Solution 2 - Python

Couldn't you have just made it a tuple in the first place? Why do you have to do:

>>> ".wmv".endswith(tuple(ext))

Couldn't you just do:

>>> ext = (".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
                        ".rm", ".swf", ".vob", ".wmv")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuillaumeView Question on Stackoverflow
Solution 1 - PythonSukrit KalraView Answer on Stackoverflow
Solution 2 - PythonPatrickView Answer on Stackoverflow