简体   繁体   中英

Remove string with brackets in List (Python)

I have a list

thislist = ["apple (red)", "banana (yellow)", "cherry (red)"]

How do I remove/strip off the brackets in each item of the list?

Desire Output:

thislist = ["apple red", "banana yellow", "cherry red"]

Thank you

Use this code:

newlist = []
for nn in thislist:
    newlist.append(nn.replace('(','').replace(')',''))
newlist

Output:

['apple red', 'banana yellow', 'cherry red']

You can use translate()

>>> thislist = ["apple (red)", "banana (yellow)", "cherry (red)"]
>>> 
>>> bad_char_dict = {"(": "", ")": ""}
>>> table = str.maketrans(bad_char_dict)
>>> 
>>> new_list = []
>>> for item in thislist:
...     new_list.append(item.translate(table))
>>> 
>>> new_list
['apple red', 'banana yellow', 'cherry red']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM