在python中反转字符串中的子字符串

Ars*_*aba 4 python substring python-3.x

我正在编写一个程序来反转 python 中括号内的子字符串。结果字符串不应包含任何括号。我正在打印 b1 和 b2 以及 ch 以进行测试。似乎在 while 循环内的 for 循环的第二次迭代中,b1 变量未使用正确的索引进行更新。我尝试编写如下解决方案:

def reverseParentheses(s):
    r = s
    sstring = ''
    astring = ''
    b1 = b2 = 0
    count = 0
    for ch in s:
        if ch == '(':
            count+=1
        elif ch ==')':
            count+=1
        else:
            pass

    while True:
        b1 = b2 = 0
        for ch in r:
            if ch == '(':
                b1 = r.index(ch)
                print("b1= ",b1, ch)
            if ch == ')':
                b2 = r.index(ch)
                print("b2= ",b2, ch)
                sstring = r[b2-1:b1:-1]
                print(r)
                print(sstring)
                astring = r[0:b1]+sstring+r[b2+1:]
                print(astring)
                r = astring
                break
        if len(astring)+count == len(s):
            break
    return r



s = "a(bcdefghijkl(mno)p)q"
print(reverseParentheses(s))
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:aonmpbcdefghijklq 这是我期望的输出:apmnolkjihgfedcbq

Mar*_*yer 6

处理嵌套分隔符的一个好方法是使用堆栈。当遇到开始分隔符时,将新集合推送到堆栈。pop()当你找到一个结束的时候。这将使嵌套顺序保持正确。

这是执行此操作的一种方法(它不检查平衡括号,但添加并不难):

s = "a(bcdefghijkl(mno)p)q"
stack = [[]] # accumulate letters in stack[0]
for l in s:
    if l == '(':
        stack.append([])        # start a new level
    elif l == ')':
        sub = stack.pop()[::-1] # pop the last level and reverse
        stack[-1].extend(sub)   # add to current 
    else:
        stack[-1].append(l)     # add to current

''.join(stack[0]) #'apmnolkjihgfedcbq'
Run Code Online (Sandbox Code Playgroud)