Related Articles

Related Articles

Python | Filter list of strings based on the substring list
  • 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.

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']

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :