Sometimes, we want to check if a string contains an element from a list in Python.
In this article, we’ll look at 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?
To check if a string contains an element from a list in Python, we can use the any function.
For instance, we write:
extensions_to_check = ['.txt', '.csv']
url_string = 'test.txt'
if any(ext in url_string for ext in extensions_to_check):
print(url_string)
We use ext in url_string for ext in extensions_to_check to check if the url_string includes the string is in the extensions_to_check list.
And we use the returned generator with any to do the check.
Since this is True, we see 'test.txt' printed.
Conclusion
To check if a string contains an element from a list in Python, we can use the any function.