[英]Python Replace text inside brackets with it's eval
我有一个文件(或字符串,如果需要的话),像这样:
$((2+1))
bbb$((2+0))a()
$((1+1))$((5**2))
$((variable+1))
我希望输出是这样的(如果变量= 1):
3
bbb2a()
225
2
基本上,首先我需要在$((和))之间获取文本,我可以这样做:
re.search(rf"\$\(\((.*?)\)\)",template).group(1)
因此,我需要用上一步中得到的所有值替换所有发生的情况。 我该怎么做? 我可以以某种方式之前编译正则表达式并将其用于获取文本和替换文本吗? 谢谢
您不需要使用任何库。 您所需要的只是使用python内置函数。
m = ["$((2+1))","$((2+0))","$((1+1))aa$((5**2))bb","$((0+0))"]
def OPGetter(string) :
i = 0
while i < len(string) :
if string[i] == ")" :
last = i
i += 1
res1 = (string[last+1:])
#
i = 0
while i < len(string) :
if string[i] == "(" :
one = i+1
i += 1
i = 0
while i < len(string) :
if string[i] == ")" :
two = i
break
i += 1
return [string[one:two],res1]
result =[]
i = 0
while i < len(m) :
string = m[i].split("$")
if len(string) > 0 :
res = string[0]
string = string[1:]
for item in string :
code = "def returning() :\n return "+ OPGetter(item)[0]
exec(code)
value = returning()
res += str(value)+OPGetter(item)[1]
result.append(res)
i += 1
结果将是答案的最终列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.