Skip to main content
How To python find in string

How To Match String Item into List Python

This tutorial help to find python list item contains a string. I’ll walk you through the many circumstances for finding items in a Python list..

I have also shared How To Find Substring and Character into String. I’ve given an example utilizing the find() method, as well as the operator and index functions.

You can also checkout other python list tutorials:

How To First Match Element found

To find an element, I’ll utilize the python in operator. This aids in determining whether or not an element is present in the list of items.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456']
if any("test" in s for s in user_list):
 print("found");
else:
 print("not found")

The Result:

found

The above code will check a string is exist or not in the list.

Get All Matched Items in Python

Sometimes, We need to get all items which are containing the required substring. we’ll search substring into the python list and return all matched items that have substring.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matching = [s for s in user_list if "test" in s]
print(matching)
$python main.py
['samtest456', 'test123']

The above code’ll return all matched items from the source python list.

How To Match Against More Than One String

Let’s match more than one substring into the python list. We can combine two comprehensions and search into the list items.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matchers = ['test','adam']
matching = [s for s in user_list if any(xs in s for xs in matchers)]
print(matching);

The Results:

$python main.py
['adam789', 'samtest456', 'test123']

Python Filter To All Matched Items

The python filter is used to find all matching elements from the python list.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matching = filter(lambda s: 'test' in s, user_list)
print(matching);

The Results:

$python main.py
['samtest456', 'test123']

Match Items Using Contains Private Method

You can also use the python contains method to find element exists or not into the python list. The __contains__() method of Pythons string class.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
substr = "test"
for i in user_list:
    if i.__contains__(substr) :
        print(i, " is containing "+substr)

Results:

$python main.py
('samtest456', ' is containing test')
('test123', ' is containing test')

3 thoughts to “How To Match String Item into List Python”

Leave a Reply

Your email address will not be published. Required fields are marked *