检查字符串是否以列表中的字符串之一结尾 [英] Check if string ends with one of the strings from a list

查看:71
本文介绍了检查字符串是否以列表中的字符串之一结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写以下代码的pythonic方式是什么?

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

我有一个模糊的记忆,可以避免for循环的显式声明,并以if条件编写.这是真的吗?

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?

推荐答案

虽然尚未广为人知,但 str.endswith 也接受一个元组.您不需要循环.

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

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

这篇关于检查字符串是否以列表中的字符串之一结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆