How to use trim strings in a list comprehension?

Question:

keywords = ['a', 'b', '(c)']
keywords = [keyword for keyword in keywords if "(" in keyword and ")" in keyword]

I want the output to be:

keywords = ['a', 'b', 'c']

How to modify the list comprehension to get the result without using a loop?

Asked By: marlon

||

Answers:

Try strip:

>>> keywords = ['a', 'b', '(c)']
>>> [kw.strip('()') for kw in keywords]
['a', 'b', 'c']
>>>
Answered By: gog

strip works. Alternate solution using replace() as well:

>>> keywords = ['a', 'b', '(c)']
>>> [kw.replace('(','').replace(')','') for kw in keywords]
['a', 'b', 'c']
Answered By: Squirtle

A list comprehensions in Python is a type of loop

Without using a loop:

keywords = ['a', 'b', '(c)']
keywords = list(map(lambda keyword: keyword.strip('()'), keywords))
Answered By: Arifa Chan
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.