Just use str.translate():

In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'

From the documentation:

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

If -- for educational purposes -- you'd like to code it up yourself, you could use something like:

''.join(c for c in str1 if c not in str2)
Answer from NPE on Stack Overflow
🌐
Pythoninformer
pythoninformer.com › python-language › intermediate-python › for-filter
PythonInformer - Looping over selected items
This isn't too hard with a simple two line loop body, but it is less obvious in complex code. In this case, the function we are using is only a single line of code, so we can use a lambda function instead of a function declaration. This definition creates an unnamed lambda function equivalent to longer_than_3: ... values = ['a', 'bcd', 'efgh', 'pqrst', 'yz'] for v in filter(lambda x: len(x) > 3, values): print(v) do_other_stuff()
🌐
KDnuggets
kdnuggets.com › 2022 › 11 › 5-ways-filtering-python-lists.html
5 Ways of Filtering Python Lists - KDnuggets
November 14, 2022 - In our case, we are running the loop over all of the list elements and selecting the score that is greater than or equal to 150. It is easy to write, and you can even add multiple if-else conditions without an issue. Learn list comprehension with code examples by reading When to Use a List Comprehension in Python. scores = [200, 105, 18, 80, 150, 140] filtered_scores = [s for s in scores if s >= 150] print(filtered_scores) ... To filter the string list, we will use `re.match()`. It requires the string pattern and the string.
Discussions

python - Filtering Characters from a String - Stack Overflow
I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed. First thing is to iterate over str1 with a for loop, then compare... More on stackoverflow.com
🌐 stackoverflow.com
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
python - Filtering a list of strings based on contents - Stack Overflow
Copy# To support matches from the ... = 'ab' filter(lambda x: x.startswith(prefix), items) ... Save this answer. ... Show activity on this post. ... Why does this work? Because the in operator is defined for strings to mean: "is substring of". Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used ... More on stackoverflow.com
🌐 stackoverflow.com
Python filter function in for loop - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I got an issue when using filter-function in for loop. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 - Inside the comprehension, the any() function checks if any substring from subs is present in the current string. Only the strings that meet the condition are added to the result. Let’s explore some more different methods to filter list of strings based on the substring list. ... This method is more straightforward but less efficient. We use two loops: one for the list of strings and one for the list of substrings. ... s = ["learn", "python", "with", "gfg"] subs = ["le", "py"] # List of substrings to check for in the strings res = [] # List to store the result # Iterate through each string in 's' for x in s: # Iterate through each substring in 'subs' for y in subs: # If a substring 'y' is found in the string 'x' if y in x: res.append(x) # Add the string 'x' to the result list break # Exit the inner loop once a match is found print(res)
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › python-filter
Python filter: Python filter function, Python filter list, FAQs
October 14, 2021 - # list of letters letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] # function that filters vowels def filter_vowels(letter): vowels = ['a', 'e', 'i', 'o', 'u'] if(letter in vowels): return True else: return False filtered_vowels = filter(filter_vowels, letters) print('The filtered vowels are:') for vowel in filtered_vowels: print(vowel) Output The filtered vowels are: a e i o · In the example given below, we have a list of letters and we need to present the vowels from the given list. For this, we can use the for loop.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-the-python-filter-function
How To Use the Python Filter Function | DigitalOcean
July 24, 2020 - The Python built-in filter() function can be used to create a new iterator from an existing iterable (like a list or dictionary) that will efficiently filter out elements using a function that we provide. An iterable is a Python object that can be “iterated over”, that is, it will return items in a sequence such that we can use it in a for loop.
🌐
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
Top answer
1 of 2
4

filter returns a generator, which is why you only obtain a list after passing the generator to list(), which takes all the elements generated and returns them in a list.

A way to get what you want without filter() and using for:

nums = list(range(1, 15))
result = [x for x in nums for i n range(2, 5) if x % i == 0]

This is called a list comprehension and it's very efficient and readable way of constructing a list like this.

2 of 2
1

Filter is generator. Therefore it uses lazy evaluation of expression. From documentation:

Variables used in the generator expression are evaluated lazily when the __next__() method is called for the generator object (in the same fashion as normal generators).

It means that lambda expression is evaluated when you call list(nums) because it calls __next__() method under the hood.

So in your second example it will (I guess) filter 3 times always with divider 4:

nums = filter(lambda x: x % 4 == 0)
nums = filter(lambda x: x % 4 == 0)
nums = filter(lambda x: x % 4 == 0)

Maybe that piece of code gives you better understanding. Notice that expression is evaluated when list() is called. As you can see, loop here doesn't change the result. Using variable i makes the difference:

nums = list(range(1, 15))
i = 2
nums = filter(lambda x: x % i == 0, nums)
i = 3
nums = filter(lambda x: x % i == 0, nums)
i = 4
nums = filter(lambda x: x % i == 0, nums)
print(list(nums)) # here i==4
### [4, 8, 12]

nums = list(range(1, 50))
for i in range(2, 5):
   nums = filter(lambda x: x % i == 0, nums)
i = 11
print(list(nums)) # here i==11
### [11, 22, 33, 44]

One more solution:

def f(x):
   for i in range(2, 5):
      if x % i != 0:
         return False
   return True

nums = list(range(1, 15))
nums = filter(f, nums)
print(list(nums))
🌐
Towards Data Science
towardsdatascience.com › home › latest › lists in python
Lists in Python | Towards Data Science
January 27, 2025 - Try modifying the condition to filter by song or a different string value for the artist. Let’s move on the ‘index-based for loops’.
🌐
TechBeamers
techbeamers.com › python-filter-function
Python Filter Function - TechBeamers
November 30, 2025 - The first argument is the name of a user-defined function, and the second is iterable like a list, string, set, tuple, etc. It calls the given function for every element of the iterable, just like in a loop.
Top answer
1 of 2
3

Check out pandas.Series.str.contains, which you can use as follows.

df[~df.tweets.str.contains('filter_word')]

MWE

In [0]: df = pd.DataFrame(
            [[1, "abc"],
             [2, "bce"]],
            columns=["number", "string"]
        )    
In [1]: df
Out[1]: 
   number string
0       1    abc
1       2    bce

In [2]: df[~df.string.str.contains("ab")]
Out[2]: 
   number string
1       2    bce

Timing

Ran a small timing test on the following synthetic DataFrame with three million random strings the size of a tweet

df = pd.DataFrame(
    [
        "".join(random.choices(string.ascii_lowercase, k=280))
        for _ in range(3000000)
    ],
    columns=["strings"],
)

and the keyword abc, comparing the original solution, map + regex and this proposed solution (str.contains). The results are as follows.

original       99s
map + regex    21s
str.contains  2.8s
2 of 2
0

I create the following example:

df = pd.DataFrame("""Suggested order for Amazon Prime Doctor Who series
Why did pressing the joystick button spit out keypresses?
Why tighten down in a criss-cross pattern?
What exactly is the 'online' in OLAP and OLTP?
How is hair tissue mineral analysis performed?
Understanding the reasoning of the woman who agreed with King Solomon to "cut the baby in half"
Can Ogre clerics use Purify Food and Drink on humanoid characters?
Heavily limited premature compiler translates text into excecutable python code
How many children?
Why are < or > required to use /dev/tcp
Hot coffee brewing solutions for deep woods camping
Minor traveling without parents from USA to Sweden
Non-flat partitions of a set
Are springs compressed by energy, or by momentum?
What is "industrial ethernet"?
What does the hyphen "-" mean in "tar xzf -"?
How long would it take to cross the Channel in 1890's?
Why do all the teams that I have worked with always finish a sprint without completion of all the stories?
Is it illegal to withhold someone's passport and green card in California?
When to remove insignificant variables?
Why does Linux list NVMe drives as /dev/nvme0 instead of /dev/sda?
Cut the gold chain
Why do some professors with PhDs leave their professorships to teach high school?
"How can you guarantee that you won't change/quit job after just couple of months?" How to respond?""".split('\n'), columns = ['Sentence'])

You can juste create a simple function with regular expression (more flexible in case of capital characters):

def tweetsFilter(s, keyword):
    return bool(re.match('(?i).*(' + keyword + ').*', s))

This function can be called to obtain the boolean series of strings which contains the specific keywords. The mapcan speed up your script (you need to test!!!):

keyword = 'Why'
sel = df.Sentence.map(lambda x: tweetsFilter(x, keyword))
df[sel]

And we obtained:

    Sentence
1   Why did pressing the joystick button spit out ...
2   Why tighten down in a criss-cross pattern?
9   Why are < or > required to use /dev/tcp
17  Why do all the teams that I have worked with a...
20  Why does Linux list NVMe drives as /dev/nvme0 ...
22  Why do some professors with PhDs leave their p...
🌐
Real Python
realpython.com › python-filter-function
Python's filter(): Extract Values From Iterables – Real Python
July 31, 2023 - Since filter() is written in C and is highly optimized, its internal implicit loop can be more efficient than a regular for loop regarding execution time. This efficiency is arguably the most important advantage of using the function in Python.
🌐
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. This function can be applied to strings or used to remove null values.
🌐
W3Schools
w3schools.com › python › ref_func_filter.asp
Python filter() Function
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... ages = [5, 12, 17, 18, 24, 32] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc, ages) for x in adults: print(x) Try it Yourself »
🌐
GeeksforGeeks
geeksforgeeks.org › filter-in-python
filter() in python - GeeksforGeeks
Let us see a few examples of the filter() function in Python. For concise conditions, we can use a lambda function instead of defining a named function.
Published   December 11, 2024
🌐
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 - One of the simplest ways to separate numbers and letters from a string is to use the isdigit() and isalpha() methods. These methods are built-in to Python and allow you to check if a character is a digit or a letter, respectively.