This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

Answer from Eli Bendersky on Stack Overflow
Discussions

Trying to create a function that will filter out strings in my list
Of course you can. You can use isinstance to determine if a value is a certain datatype. Here's a usage examples value = "hello world" isinstance(value, str) # True value = 42 isinstance(value, are) # False EDIT: After re-reading your question, I'm not sure if you meant that you wanted to remove all strings or specific strings from your list. If it's the former, my answer stands. If it's the latter, just say so and I will adapt my answer. More on reddit.com
🌐 r/learnpython
3
1
January 31, 2023
SQLALCHEMY, how do I filter a text column by any word in a search list?
You should look into using ilike to search your text column. Source from flask_sqlalchemy import SQLAlchemy as db class YourModel(db.Model): some_text = db.Column(db.String(500)) def __init__(self, **kwargs): super(YourModel, self).__init__(**kwargs) @classmethod def search(cls, query): if not query or not isinstance(query, str): raise ValueError("Missing query arg as a string") search_query = "%{0}%".format(query) return cls.query.filter(cls.some_text.ilike(search_query).all() More on reddit.com
🌐 r/flask
4
2
January 9, 2020
Flask SQLAlchemy dynamic filter on sub-string of column value
I think you can do... from sqlalchemy import func systems.filter(func.substr(Inventory.hostname, 9, 3).in_(mtypes.split(','))) More on reddit.com
🌐 r/flask
1
4
August 28, 2019
Do I have to sanitize inputs to SQLAlchemy query.filter calls?
Your like filter there isn't vulnerable to sql injections, but it is to users submitting their own wildcards. You might want to escape the users submission for %, _, or \ yourself. I use https://sqlalchemy-utils.readthedocs.io/en/latest/orm_helpers.html#sqlalchemy_utils.functions.escape_like More on reddit.com
🌐 r/flask
8
15
January 12, 2021
🌐
IONOS
ionos.com › digital guide › websites › web development › python filter function
What is Python's filter function and how to use it - IONOS
May 26, 2025 - Python’s filter() function allows you to filter an iterable using a condition. Python then creates a new iterator that only includes the elements that meet the specified condition.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-list-of-strings-based-on-the-substring-list
Python - Filter list of strings based on the substring list - GeeksforGeeks
July 11, 2025 - The lambda function uses any to check if a string contains any of the substrings from subs. The filter function returns an iterator, which we convert into a list. We can use the re module to solve this problem.
🌐
W3Schools
w3schools.com › python › ref_func_filter.asp
Python filter() Function
The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
🌐
Noble Desktop
nobledesktop.com › filtering a string with python
Filtering a String with Python
June 5, 2025 - The method 'count' is utilized to find the frequency of a character in a string in Python. A 'for loop' can be used for more advanced filtering within strings.
🌐
Linux Hint
linuxhint.com › filter_list_strings_python
How to filter a list of strings in Python – Linux Hint
Python uses list data type to store multiple data in a sequential index. It works like a numeric array of other programming languages. filter() method is a very useful method of Python. One or more data values can be filtered from any string or list or dictionary in Python by using filter() method.
Find elsewhere
🌐
w3resource
w3resource.com › python-exercises › filter › python-filter-exercise-9.php
Python function to filter strings with a specific substring
Use the filter function to filter out strings from the strings list by applying the "contains_substring()" function as the filtering condition. Finally, the filtered strings containing the specified substring are converted to a list and returned ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-in-python
filter() in python - GeeksforGeeks
Explanation: filter(None, L) removes all falsy values (empty string, None and 0) and keeps only truthy ones. Comment · Python Fundamentals · Introduction1 min read · Input & Output2 min read · Variables4 min read · Operators4 min read · ...
Published   March 18, 2026
🌐
Towards Data Science
towardsdatascience.com › home › latest › 5 methods for filtering strings with python pandas
5 Methods for Filtering Strings with Python Pandas | Towards Data Science
January 24, 2025 - We can filter based on the first or last letter of a string using the startswith and endswith methods, respectively. ... These methods are able to check the first n characters as well. For instance, we can select rows in which the lot value starts with ‘A-0’: ... Python has some built-in string functions, which can be used for filtering string values in Pandas DataFrames.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › python-filter
Python filter: Python filter function, Python filter list, FAQs
October 14, 2021 - The filter(function, iterable) function takes a function as an argument and returns a Boolean value indicating whether this list entry should pass the filter. All elements that pass are returned as a new iterable object by the filter (a filter ...
🌐
Programiz
programiz.com › python-programming › methods › built-in › filter
Python filter()
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] # a function that returns True if letter is vowel def filter_vowels(letter): vowels = ['a', 'e', 'i', 'o', 'u'] if letter in vowels: return True else: return False
🌐
Mimo
mimo.org › glossary › python › filter
Python filter(): Syntax, Usage, and Examples
You can use the filter() function in Python to extract elements from a sequence that meet a certain condition. Instead of writing a full loop with if statements, the Python filter() function lets you express filtering logic in a clear and concise way.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-supersequence-strings
Python - Filter Supersequence Strings - GeeksforGeeks
July 23, 2025 - The original list is : ['gfg', '/', 'geeksforgeeks', 'best', 'for', 'geeks'] Filtered strings : ['geeksforgeeks', 'geeks'] ... In this, we perform task of filtering using filter() and lambda function rather than list comprehension and conditionals ...
🌐
TechBeamers
techbeamers.com › python-filter-function
Python Filter Function - TechBeamers
November 30, 2025 - """ Desc: Python program to remove stop words from string using filter() function """ # List of stop words list_of_stop_words = ["in", "of", "a", "and"] # String containing stop words string_to_process = "a citizen of New York city fought and ...
🌐
Medium
medium.com › data-science › 5-methods-for-filtering-strings-with-python-pandas-ebe4746dcc74
5 Methods for Filtering Strings with Python Pandas | by Soner Yıldırım | TDS Archive | Medium
August 11, 2022 - Pandas library has lots of functions and methods that make working with textual data easy and simple. In this article, we will learn 5 different methods that can be used for filtering textual data (i.e. strings):
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-string-with-substring-at-specific-position
Python | Filter String with substring at specific position - GeeksforGeeks
April 13, 2023 - In this, we filter the elements using logic compiled using lambda using filter(). ... # Python3 code to demonstrate # Filter String with substring at specific position # using filter() + lambda # Initializing list test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list is : " + str(test_list)) # Initializing substring sub_str = 'geeks' # Initializing range i, j = 0, 5 # Filter String with substring at specific position # using filter() + lambda res = list(filter(lambda ele: ele[i: j] == sub_str, test_list)) # printing result print ("Filtered list : " + str(res))
🌐
Code With Pere
pere.hashnode.dev › python-tips-how-to-filter-numbers-and-letters-from-a-string
Python Tips: How to Filter Numbers and Letters from a String
December 29, 2022 - Another option for separating numbers and letters from a string is to use the filter() function. This function takes a function and an iterable as input and returns an iterator that only includes items from the iterable for which the function ...
🌐
Finxter
blog.finxter.com › 5-best-ways-to-filter-a-list-of-strings-in-python-based-on-substring
5 Best Ways to Filter a List of Strings in Python Based on Substring – Be on the Right Side of Change
February 18, 2024 - patterns = ['an', 'er'] strings = ['apple', 'banana', 'cherry', 'date'] filtered_strings = [s for s in strings if any(sub in s for sub in patterns)] print(filtered_strings) ... This snippet efficiently searches for multiple substrings within the elements of a list. It uses a list comprehension combined with an any() expression that iterates through each potential substring and includes a string in the output list if any of the substrings match. Method 1: List Comprehension. Straightforward and Pythonic.