Testing if string contains an element fromlist is checking whether any of the individual items in a list appear within a given string.
any()is the most efficient way to check if any element from the list is present in the list.
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 expressionres=any(eleminsforeleminel)print(res)
True
Let's explore some more methods to check how we can test if string contains elements from a list.
Table of Content
This approach explicitly iterates through the list using afor loop to check for the presence of elements in the string.
s="Python is powerful and versatile."el=["powerful","versatile","fast"]# Initialize the result variable to Falseres=False# Iterate through each element in the listforeleminel:ifelemins:res=Truebreakprint(res)
Using set intersection method is effective when both the string and the list of elements are relatively short.
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)
Regular expressionsprovide flexibility for more complex matching scenarios but are less efficient for simple tasks.
importres="Python is powerful and versatile."el=["powerful","versatile","fast"]# Compile a regular expression pattern to search for any of the elements in the listpattern=re.compile('|'.join(map(re.escape,el)))res=bool(pattern.search(s))print(res)
M
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers