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

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


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)

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 e.g. in the ending of the string. 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.


extensionsToCheck = ('.pdf', '.doc', '.xls')'test.doc'.endswith(extensionsToCheck)   # returns True'test.jpg'.endswith(extensionsToCheck)   # returns False


It is better to parse the URL properly - this way you can handle http://.../file.doc?foo and http://.../foo.doc/file.exe correctly.

from urlparse import urlparseimport ospath = urlparse(url_string).pathext = os.path.splitext(path)[1]if ext in extensionsToCheck:  print(url_string)