简体   繁体   English

计算 python 中字符串中的表达式

[英]Evaluate expression in a string in python

I have a string with mathematical operations, how do I evaluate the string within [] to generate the output shown below?我有一个带有数学运算的字符串,如何评估[]中的字符串以生成如下所示的 output?

mystring = "[2*3-1] plus [4+2] is equal to [5+6]."

re.findall(r"\[(.*?)\]",mystring) # to find 2*3-1, 4+2, 5+6

Output: "5 plus 6 is equal to 11." # expected output. 

You may use re.sub with eval and a callback function here:您可以在此处将re.subeval和回调 function 一起使用:

mystring = "[2*3-1] plus [4+2] is equal to [5+6]."
output = re.sub(r'\[(.*?)\]', lambda m: str(eval(m.group(1))), mystring)
print(output)  # 5 plus 6 is equal to 11.

The strategy here is to match the aritrmetic expression inside every [...] , which then gets passed to a lambda function.这里的策略是匹配每个[...]中的算法表达式,然后将其传递给 lambda function。 There, we call eval() to get the result, cast to a string and generate the replacement.在那里,我们调用eval()来获取结果,转换为字符串并生成替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM