Skip to content

Python string contains any of list

  • by

Use a generator together with any() function to check string contains any of the lists in Python. This expression short-circuits on the first True.

if any(ext in string for ext in list):
    print(string)

Python string contains any of the list examples

Simple example code.

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

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

Output:

Python string contains any of list

Check if any of a list of strings is in another string

numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
s = input()

test = any(n in s for n in numbers)
print(test)

Output:

1
True

Comment if you have any doubts or suggestions on this Python string list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *