[英]Remove string with brackets in List (Python)
我有一個清單
thislist = ["apple (red)", "banana (yellow)", "cherry (red)"]
如何刪除/剝離列表中每個項目中的括號?
渴望 Output:
thislist = ["apple red", "banana yellow", "cherry red"]
謝謝
使用此代碼:
newlist = []
for nn in thislist:
newlist.append(nn.replace('(','').replace(')',''))
newlist
Output:
['apple red', 'banana yellow', 'cherry red']
您可以使用翻譯()
>>> 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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.