Skip to content
Related Articles

Related Articles

Python | Filter list of strings based on the substring list

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 29 May, 2019

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

Output:

['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))

Output:

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!