簡體   English   中英

刪除列表中帶括號的字符串(Python)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM