W3docs

How to check if a string is a substring of items in a list of strings

You can use a for loop to iterate through the list of strings, and then use the in keyword to check if the string is a substring of the current item in the list.

You can use a for loop to iterate through the list of strings, and then use the in keyword to check if the string is a substring of the current item in the list. Here is an example:

Using a for loop to check if a string is a substring of items in a list of strings in Python

def is_substring(string, string_list):
    for item in string_list:
        if string in item:
            return True
    return False

string_list = ["hello", "world", "goodbye"]
print(is_substring("wor", string_list)) # True
print(is_substring("dog", string_list)) # False

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Alternatively you can use any() with a generator expression which is more pythonic and better performant

Using a generator expression to check if a string is a substring of items in a list of strings in Python

def is_substring(string, string_list):
    return any(string in s for s in string_list)

string_list = ["hello", "world", "goodbye"]
print(is_substring("wor", string_list)) # True
print(is_substring("dog", string_list)) # False

This will return True if the string is a substring of any of the items in the list, and False otherwise.