Python | Filter list of strings based on the substring list

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

['city1', 'class5', 'city2']

 
Method #2 : Python Regex

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

['city1', 'class5', 'city2']


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.