5 Best Ways to Check If a List of Strings Is in a String in Python

πŸ’‘ Problem Formulation: Python developers often face the task of checking whether multiple substrings are present within a larger string. For instance, given the list of strings ["apple", "banana", "cherry"] and the larger string "I have an apple and a banana.", we want to ascertain if each item in the list occurs in the string. This article explains 5 efficient methods to perform this check.

Method 1: Using a For Loop and the in Operator

One straightforward method to check for the presence of each string in a list within another string is to iterate over the list using a for loop and the in operator. This basic approach doesn’t require importing any additional modules and is easy to understand, even for beginners.

Here’s an example:

substrings = ["apple", "banana", "cherry"]
text = "I have an apple and a banana."
found = [s for s in substrings if s in text]
print(found)

Output:

['apple', 'banana']

This code snippet creates a list found containing all substrings that are found in text. It iterates over each element in substrings and checks if it is present in text using the in operator within a list comprehension.

Method 2: Utilizing List Comprehension and the all() Function

When you need to check if all strings in a list are contained within another string, Python’s all() function combined with a list comprehension provides a compact and readable solution. This approach immediately returns a Boolean value based on the condition’s truthfulness for all items.

Here’s an example:

substrings = ["apple", "banana", "grape"]
text = "I have an apple, a banana, and a cherry."
result = all(s in text for s in substrings)
print(result)

Output:

False

The all() function in this snippet checks whether all elements in the substrings list appear in the text string. It processes each condition generated by the generator expression and will return True only if every condition is True.

Method 3: Using the any() Function With List Comprehension

If the goal is to check whether at least one string from a list exists in another string, Python’s any() function is ideal. This method returns a Boolean that signifies if any of the elements satisfy the condition, stopping the iteration as soon as the first True condition is found.

Here’s an example:

substrings = ["cherry", "melon", "kiwi"]
text = "I have an apple and a banana."
found_any = any(s in text for s in substrings)
print(found_any)

Output:

False

This snippet uses the any() function to determine if any of the strings in the substrings list occur in the text. The generator expression is evaluated until a True condition is met or all elements are checked.

Method 4: Using Regular Expressions

The re module in Python provides regular expression operations, which can be used to check for the presence of multiple strings within a string by combining the substrings into a single regular expression pattern. This approach is powerful and supports complex matching conditions.

Here’s an example:

import re
substrings = ["apple", "banana", "cherry"]
text = "Do you like apples and bananas?"
pattern = '|'.join(substrings)
matches = re.findall(pattern, text)
print(matches)

Output:

['apple', 'banana']

In this code, we first join the substrings into a single string pattern separated by the regex ‘or’ operator (|). The re.findall() function is then used to find all occurrences of the pattern within text. The result is a list of all matched substrings.

Bonus One-Liner Method 5: Using filter and Lambda Function

For a concise one-liner solution, Python’s filter function can be teamed up with a lambda function. This combination filters the list of substrings, leaving only those found in the target string. This approach is elegant for simple cases but may become less readable as complexity increases.

Here’s an example:

substrings = ["apple", "orange", "grape"]
text = "I have apples, oranges, and grapes in my basket."
matched = list(filter(lambda s: s in text, substrings))
print(matched)

Output:

['apple', 'orange', 'grape']

The lambda function in this snippet returns True for each item in substrings that is found in text. The filter function applies this lambda to each item and the list constructor converts the filter object to a list of matched substrings.

Summary/Discussion

  • Method 1: For Loop and in Operator. Simple to follow. Best for beginners and for cases where you don’t need to check for all substrings at once.
  • Method 2: all() Function with List Comprehension. Ideal for validating the presence of all substrings. Efficient but returns only a Boolean result.
  • Method 3: any() Function With List Comprehension. Quick for determining if any substring is present. Like method 2, it only provides a Boolean output.
  • Method 4: Using Regular Expressions. Powerful for complex pattern matching. However, it can become difficult to maintain with more elaborate patterns.
  • Bonus Method 5: filter and Lambda. Elegant for simple checks. May decrease in readability with increased complexity.