Check if String is Substring of Items in List

How to Check if String is Substring of Items in List

Python Lists are a great way to store a number of strings in a compact manner. Lists also support many useful functions making it easy to work with these string items. But sometimes python developers need to check if a string is a substring of any of the items in a python list. In this article, we will learn how to check if string is substring of items in list.


How to Check if String is Substring of Items in List

Let us say you have the following list of strings in Python.

test = ['abc-123', 'xyz-456', 'pqr-789', 'abc-456']

Let us say you want to check if string ‘abc’ is in substring of items in list. Typically, developers use the following way to check this.

if 'abc' in test:
   #do something

But the above approach does not work because python will check the list to see if there is an element exactly equal to ‘abc’, and not if ‘abc’ is a substring of it. The solution is to loop through the list and use the ‘in’ operator on each item, instead of the entire list as shown below.

So you need to use any() function for this as shown below.

if any("abc" in s for s in test):
    #do something

any() function returns true if any item in a python iterable is true, else it returns false. To get all items that contain substring ‘abc’, you need to check it this way.

>>> subs = [s for s in test if "abc" in s]
>>> print subs
['abc-123', 'abc-456']

In this article, we have learnt how to check if string is substring in Python list.

Also read:

How to Check if Column is Empty or Null in MySQL
How to Modify MySQL Column to Allow Null
How to Schedule Multiple Cron Jobs in One Crontab
How to POST JSON Data in Python
How to Remove SSL and SSH Passphrase

Leave a Reply

Your email address will not be published.