Check if a string contains an element from a list in Python

avatar

Borislav Hadzhiev

Last updated: Aug 10, 2022

banner

Photo from Unsplash

Check if a string contains an element from a list in Python #

Use the any() function to check if a string contains an element from a list, e.g. if any(substring in my_str for substring in my_list):. The any() function will return True if the string contains at least one element from the list and False otherwise.

main.py
my_str = 'one two three' my_list = ['a', 'two', 'c'] if any(substring in my_str for substring in my_list): # 👇️ this runs print('The string contains at least one element from the list') else: print('The string does NOT contain any of the elements in the list')

We used a generator expression to iterate over the collection of strings.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

In the example, we iterate over the list of strings and check if each string is contained in the other string.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

The any() function will short-circuit returning True if the string contains at least one element from the list.

You can use the assignment expression syntax if you need to get the list item that is contained in the string.

main.py
my_str = 'one two three' my_list = ['a', 'two', 'c'] if any((match := substring) in my_str for substring in my_list): # 👇️ this runs print('The string contains at least one element from the list') print(match) # 👉️ 'two' else: print('The string does NOT contain any of the elements in the list')
Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.

If the iterable we pass to the any() function is empty or none of the elements in the iterable are truthy, the any function returns False.

If you need to check if a string contains an element from a list in a case-insensitive manner, convert both strings to lowercase.

main.py
my_str = 'ONE TWO THREE' my_list = ['a', 'two', 'c'] if any(substring.lower() in my_str.lower() for substring in my_list): # 👇️ this runs print('The string contains at least one element from the list') else: print('The string does NOT contain any of the elements in the list')

We used the str.lower() method to convert each list item and the string to lowercase before checking if each list item is contained in the string.

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.