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. Here is an example:
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
Watch a video course
Python - The Practical Guide
Alternatively you can use any()
with a generator expression which is more pythonic and better performant
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.