Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr.
Examples:
Input : string = ['city1', 'class5', 'room2', 'city2'] substr = ['class', 'city'] Output : ['city1', 'class5', 'city2'] Input : string = ['coordinates', 'xyCoord', '123abc'] substr = ['abc', 'xy'] Output : ['xyCoord', '123abc']
Method #1 : Using List comprehension
We can Use list comprehension along with in operator to check if the string in ‘substr’ is contained in ‘string’ or not.
# Python3 program to Filter list of # strings based on another list import re def Filter (string, substr): return [ str for str in string if any (sub in str for sub in substr)] # Driver code string = [ 'city1' , 'class5' , 'room2' , 'city2' ] substr = [ 'class' , 'city' ] print ( Filter (string, substr)) |
['city1', 'class5', 'city2']
Method #2 : Python Regex
# Python3 program to Filter list of # strings based on another list import re def Filter (string, substr): return [ str for str in string if re.match(r '[^\d]+|^' , str ).group( 0 ) in substr] # Driver code string = [ 'city1' , 'class5' , 'room2' , 'city2' ] substr = [ 'class' , 'city' ] print ( Filter (string, substr)) |
['city1', 'class5', 'city2']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.