首页 > 解决方案 > 将字符串中的运算符插入表达式字符串

问题描述

给定一个带有变量和括号的字符串:

'a((bc)((de)f))'

和一串运算符:

'+-+-+'

我想将每个运算符(按顺序)插入以下模式之间的第一个字符串中(其中 char 定义为不是左括号或右括号的字符):

给出结果:

'a+((b-c)+((d-e)+f))'

编辑:我让它与下面的代码一起工作,但有没有更优雅的方法来做到这一点,即没有 for 循环?

    x = 'a((bc)((de)f))'
    operators = '+-+-+'
    y = x
    z = 0
    for i in range(len(x)):
        if i < len(x)-1:
            xx = x[i]
            isChar = True if x[i] != '(' and x[i] != ')' else False
            isPO = True if x[i] == '(' else False
            isPC = True if x[i] == ')' else False

            isNxtChar = True if x[i+1] != '(' and x[i+1] != ')' else False
            isNxtPO = True if x[i+1] == '(' else False
            isNxtPC = True if x[i+1] == ')' else False

            if (isChar and (isNxtChar or isNxtPO)) or (isPC and (isNxtPO or isNxtChar)):
                aa = operators[z]
                split1 = x[:i+1]
                split2 = x[i+1:]
                y = y[:i+z+1] + operators[z] + x[i+1:]
                if z+1 < len(operators):
                    z+=1
            
    print (y)

标签: pythonstring

解决方案


initialExpr = 'a((bc)((de)f))'
operators = '+-+-+'

countOp = 0
countChar = 0
for char in initialExpr:
    countChar += 1
    print(char,end='')
    if countChar < len(initialExpr) and (char == ')' or char.isalpha()) and (initialExpr[countChar] == '(' or initialExpr[countChar].isalpha()):
        print(operators[countOp], end='')
        countOp += 1

这应该可以完成这项工作。假设变量、括号和运算符的顺序和编号正确。


推荐阅读