本文介绍了使用具有多个扩展名的endswith的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测带有扩展名列表的文件.

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

推荐答案

为此使用元组.

>>> 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.

这篇关于使用具有多个扩展名的endswith的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 23:35