我有这样的 idea :

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

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

我想知道在Python中实现这一点(不使用for循环)的更优雅的方法是什么?我曾想过这样的事情(比如从C/C++),但没有成功:

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

Edit: I'm kinda forced to explain how this is different to the question below which is marked as potential duplicate (so it doesn't get closed I guess).

The difference is, I wanted to check if a string is part of some list of strings whereas the other question is checking whether a string from a list of strings is a substring of another string. Similar, but not quite the same and semantics matter when you're looking for an answer online IMHO. These two questions are actually looking to solve the opposite problem of one another. The solution for both turns out to be the same though.

推荐答案

将发电机与any一起使用,第一次短路:

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

EDIT:我看到这个答案已经被OP接受了.虽然我的解决方案可能是他特定问题的"足够好"的解决方案,并且是判断列表中的任何字符串是否在另一个字符串中找到的一种很好的通用方法,但请记住,这就是这个解决方案的全部功能.It does not care WHERE the string is found e.g. in the ending of the string.如果这一点很重要,就像URL经常出现的情况一样,你应该看看@Wladimir Palant的答案,否则你就有可能得到误报.

Python相关问答推荐

脚注在Python中使用regex导致错误匹配

当pip为学校作业(job)安装sourcefender时,我没有收到匹配的分发错误.我已经try 过Python 3.8.10和3.10.11

Django序列化器没有验证或保存数据

每个组每第n行就有Pandas

将嵌套列表的字典转换为数据框中的行

使用Python C API重新启动Python解释器

Polars Select 多个元素产品

添加包含中具有任何值的其他列的计数的列

如何处理嵌套的SON?

如何使用Google Gemini API为单个提示生成多个响应?

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

根据条件将新值添加到下面的行或下面新创建的行中

使用FASTCGI在IIS上运行Django频道

使用numpy提取数据块

Vectorize多个头寸的止盈/止盈回溯测试pythonpandas

如何找到满足各组口罩条件的第一行?

图像 pyramid .难以创建所需的合成图像

无法使用requests或Selenium抓取一个href链接

将tdqm与cx.Oracle查询集成

基于形状而非距离的两个numpy数组相似性