如何检查字符串是否包含Python中列表中的元素 [英] How to check if a string contains an element from a list in Python

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

问题描述

我有这样的事情:

extensionsToCheck = ['.pdf', '.doc', '.xls']

for extension in extensionsToCheck:
    if extension in url_string:
        print(url_string)

我想知道在python中更优雅的方法是什么(不使用for循环)?我在考虑这样的事情(比如来自c / c ++),但它不起作用:

I am wondering what would be the more elegant way to do this in python (without using the for loop)? I was thinking of something like this (like from c/c++), but it didn't work:

if ('.pdf' or '.doc' or '.xls') in url_string:
    print(url_string)


推荐答案

将生成器与任何一起使用,这会在第一个True上发生短路:

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

编辑:我看到这个答案已被OP接受。虽然我的解决方案对于他的特定问题可能是足够好的解决方案,并且是检查列表中的任何字符串是否在另一个字符串中找到的良好通用方法,但请记住,这就是此解决方案所做的全部。它不关心在哪里找到字符串。如果这很重要,就像网址的情况一样,你应该看看@Wladimir Palant的答案,否则你可能会得到误报。

I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care where the string is found. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

这篇关于如何检查字符串是否包含Python中列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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