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.

Asked By: mrbright

||

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'
Answered By: Kourosh Hassani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.