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 OverflowThis 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.
[x for x in L if 'ab' in x]
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
sthat are indeletechars(if present), and then translate the characters usingtable, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. Iftableis 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)
Use replace:
def filter_string(str1, str2):
for c in str2:
str1 = str1.replace(c, '')
return str1
Or a simple list comprehension:
''.join(c for c in str1 if c not in str2)
Trying to create a function that will filter out strings in my list
SQLALCHEMY, how do I filter a text column by any word in a search list?
Flask SQLAlchemy dynamic filter on sub-string of column value
Do I have to sanitize inputs to SQLAlchemy query.filter calls?
Videos
Is there a way I can loop through a list and filter out the strings in the list? I have the below so far
new_list = []
def num_int(str_list):
for i in str_list:
#I would want to loop though my list and filter out the strings. Can I do an if statement based on a datatype check?