繁体   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