How to remove items from a string that are not contained in a list in Python
Question:
I have a list of items:
items =["a", "b", "c"]
Now I want to scan a string containing the elements:
string = "a, b, c, d, e"
And remove d and e to get the following string of elements:
string = "a, b, c"
I have tried to use the remove() operator but it doesn’t solve the problem. I would appreciate your help. Thanks.
Answers:
items = ["a", "b", "c"]
string = "a, b, c, d, e"
', '.join([i for i in string.split(', ') if i in items])
output:
'a, b, c'
I have a list of items:
items =["a", "b", "c"]
Now I want to scan a string containing the elements:
string = "a, b, c, d, e"
And remove d and e to get the following string of elements:
string = "a, b, c"
I have tried to use the remove() operator but it doesn’t solve the problem. I would appreciate your help. Thanks.
items = ["a", "b", "c"]
string = "a, b, c, d, e"
', '.join([i for i in string.split(', ') if i in items])
output:
'a, b, c'