在python3中将字符串方程分成两部分
问题描述:
我有一个字符串,如 '(((a+b)+a)+c)'
,我想分成两部分,结果是('((a+b)+a)','c')
。在python3中将字符串方程分成两部分
如果我要的结果的第一个元素上再次运行它,它会给我('(a+b)', 'a')
,如果我又跑它'(a+b)'
它会返回('a', 'b')
。
我想我可以通过一个正则表达式做到这一点,但我不知道这一点,然后走下路径有许多if语句检查打开和关闭括号,但它变得有点凌乱
答
这里是上的例子,如你的工作的一个示例:
def breakit(s):
count = 0
for i, c in enumerate(s):
if count == 1 and c in '+-':
return s[1:i].strip(), s[i+1:-1].strip()
if c == '(': count +=1
if c == ')': count -= 1
return s
breakit(s)
>> ('((a+b)+a)', 'c')
breakit(_[0])
('(a+b)', 'a')
breakit(_[0])
('a', 'b')
答
瞧的:
#!/usr/bin/python3.5
def f(s):
p=s.rsplit('+',1)
return [p[0][1:],p[1][:-1]]
s='(((a+b)+a)+c)'
for i in range(3):
k=f(s)
s=k[0]
print(k)
输出:
['((a+b)+a)', 'c']
['(a+b)', 'a']
['a', 'b']
+0
分割出来,并不适用于所有情况。 – dimebucker91
答
我想我会发布我的回答为好,不是很优雅的选择的解决方案,但它的工作原理
def break_into_2(s):
if len(s) == 1:
# limiting case
return s
# s[0] can either be a digit or '('
if s[0].isdigit():
# digit could be 10,100,1000,...
idx = 0
while s[idx].isdigit():
idx += 1
a = s[:idx]
b = s[idx+1:]
return a, b
# otherwise, s[0] = '('
idx = 1
counter = 1
# counter tracks opening and closing parenthesis
# when counter = 0, the left side expression has
# been found, return the idx at which this happens
while counter:
if s[idx] == '(':
counter+=1
elif s[idx] == ')':
counter -=1
idx +=1
if s[:idx] == s:
# this case occurs when brackets enclosing entire expression, s
# runs the function again with the same expression from idxs 1:-1
return break_into_2(s[1:-1])
return s[:idx], s[idx+1:]
不知道这是怎么太广... – dimebucker91
自发性我说你需要一个解析器。 – klutt
@ dimebucker91你真正想要做的是解决操作或简单地拆分字符串? (((a + b)+ c)+(a + b))( –