python - 将字符串中的运算符插入表达式字符串
问题描述
给定一个带有变量和括号的字符串:
'a((bc)((de)f))'
和一串运算符:
'+-+-+'
我想将每个运算符(按顺序)插入以下模式之间的第一个字符串中(其中 char 定义为不是左括号或右括号的字符):
- char 后跟 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)
解决方案
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
这应该可以完成这项工作。假设变量、括号和运算符的顺序和编号正确。
推荐阅读
- python - 如何获取由 redditors 列表发布的所有提交和评论?
- bash - 重定向到文件时,Grep 输出不可读
- php - 问:PayPal REST API PHP:如何获取付款详情?
- javascript - 返回新形式的数组 - javascript
- c# - 显示整个 GridView 行的工具提示
- spring - 在 Spring Boot 应用程序中从外部 JAR 加载模型和 DAO
- excel - Excel VBA 循环优化 - j = 2 时退出
- r - 循环遍历 R 中后续行中的 NA 值
- maven - Maven项目中将java类导入Jsp
- c# - 从 Mac 上的 Rider 附加到 Azure Functions 的调试器