Home > Software design >  How to use trim strings in a list comprehension?
How to use trim strings in a list comprehension?

Time:09-29

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?

CodePudding user response:

Try strip:

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

CodePudding user response:

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))

CodePudding user response:

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

>>> keywords = ['a', 'b', '(c)']
>>> [kw.replace('(','').replace(')','') for kw in keywords]
['a', 'b', 'c']
  • Related