Python Test if string contains element from list (original) (raw)

Last Updated : 08 Jan, 2025

Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string.

Using any() with a generator expression

any() is the most efficient way to check if any element from the list is present in the list.

Python `

s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]

Check if any element in the list exists in the string

using any() and a generator expression

res = any(elem in s for elem in el) print(res)

`

Explanation:

Let’s explore some more methods to check how we can test if string contains elements from a list.

Table of Content

Using a for loop

This approach explicitly iterates through the list using a for loop to check for the presence of elements in the string.

Python `

s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]

Initialize the result variable to False

res = False

Iterate through each element in the list

for elem in el: if elem in s: res = True break

print(res)

`

Explanation:

Using set intersection

Using set intersection method is effective when both the string and the list of elements are relatively short.

Python `

s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]

Split the string into individual words using the split() method'

res = bool(set(s.split()) & set(el))

print(res)

`

Explanation:

Using regular expressions

Regular expressions provide flexibility for more complex matching scenarios but are less efficient for simple tasks.

Python `

import re

s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]

Compile a regular expression pattern to search for any of the elements in the list

pattern = re.compile('|'.join(map(re.escape, el))) res = bool(pattern.search(s)) print(res)

`

Explanation:

Similar Reads