Python 从列表中的元素中删除括号
我是python的初学者,还没有做过正则表达式。我试图从列表中的元素中去掉“(”和“)”。我尝试了以下方法,但不起作用Python 从列表中的元素中删除括号,python,Python,我是python的初学者,还没有做过正则表达式。我试图从列表中的元素中去掉“(”和“)”。我尝试了以下方法,但不起作用 def trial(st): a=st.split() ls=[] for item in a: ls.append(item.replace('(','')) return a >>>trial("( +( + 8 7)( + 2 5 ))") ['(', '
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', '))']
我正试图获得以下信息:
>>>trial("( +( + 8 7)( + 2 5 ))")
['+', '+', '8', '7', '+', '2', '5']
为什么不先去掉括号呢
a = st.replace("("," ").replace(")"," ").split()
正则表达式在这里非常有用:
>>> import re
>>> s = "( +( + 8 7)( + 2 5 ))"
>>> re.findall("[+0-9]+",s)
['+', '+', '8', '7', '+', '2', '5']
如果您没有学习过正则表达式:
>>> [x for x in s if x=='+' or x.isdigit()]
['+', '+', '8', '7', '+', '2', '5']
str.isdigit()将检查字符串是否为数字它与
字符串一样简单。替换(“(”,”).replace(“),”).split()
。。。但是我能问一下这是为什么吗?我计算这个表达式得到22。这是错误的方法。使用堆栈。在这里阅读更多:谢谢你为我指明了正确的道路。但我已经有了一个工作代码。不过,我的算法与本文所讨论的非常相似。谢谢第二个版本假定为一位数numbers@ScottHunter是一位数