[英]removing parenthesis from elements in list
I am a beginner in python and I have not done regex. 我是python的初学者,但是我没有做过正则表达式。 I am trying to get rid of '(' and ')' from elements in a list.
我试图摆脱列表中元素的“(”和“)”。 I tried the following but it does not work.
我尝试了以下操作,但不起作用。
def trial(st):
a=st.split()
ls=[]
for item in a:
ls.append(item.replace('(',''))
return a
>>>trial("( +( + 8 7)( + 2 5 ))")
['(', '+(', '+', '8', '7)(', '+', '2', '5', '))']
I am trying to get the following: 我正在尝试获得以下信息:
>>>trial("( +( + 8 7)( + 2 5 ))")
['+', '+', '8', '7', '+', '2', '5']
为什么不先删除括号?
a = st.replace("("," ").replace(")"," ").split()
Regex is quite usefull here: 正则表达式在这里非常有用:
>>> import re
>>> s = "( +( + 8 7)( + 2 5 ))"
>>> re.findall("[+0-9]+",s)
['+', '+', '8', '7', '+', '2', '5']
if you dont have studied regex: 如果您没有学习过正则表达式:
>>> [x for x in s if x=='+' or x.isdigit()]
['+', '+', '8', '7', '+', '2', '5']
str.isdigit() will check is the string is digit or not str.isdigit()将检查字符串是否为数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.