Python - Check if String contains Substring from List
Check if string contains substring(s) from list in Python
To check if string contains substring from a list of strings, iterate over list of strings, and for each item in the list, check if the item is present in the given string.
In this type of scenario, we have
- a source string, in which we have to check if some substring is present.
- a list of strings, whose elements may occur in the source string, and we have to find if any of these strings in the list occur in source string.
Examples
1. Check if given string contains items from list
In this example, we will take a source string, and a list of strings. We will use for loop, to check if the string from list is present as substring in source string.
Python Program
source_string = 'a b c d e f'
list_of_strings = ['k', 'm', 'e' ]
for substring in list_of_strings:
if substring in source_string:
print('String contains substring from list.')
break
Output
String contains substring from list.
As the item from list 'e'
is present as substring in the source string, during the for loop execution for the element 'e'
, condition in if loop becomes True.
Summary
In this tutorial of Python Examples, we learned how to check if string contains substring from a list of strings, with the help of example program.