pootzko pootzko - 1 year ago 134
Python Question

How to check if a string contains an element from a list in Python

I have something like this:

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

for extension in extensionsToCheck:
if extension in url_string:

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:

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download