Python-评估字符串中的数学表达式 [英] Python - Evaluate math expression within string
问题描述
我有一个关于字符串中数学表达式求值的问题. 例如,我的字符串如下:
I have a question concerning evaluation of math expression within a string. For example my string is following:
my_str='I have 6 * (2 + 3) apples'
我想知道如何评估此字符串并获得以下结果:
I am wondering how to evaluate this string and get the following result:
'I have 30 apples'
有什么办法吗?
谢谢.
P.S. python的eval
函数在这种情况下无济于事.尝试使用eval
函数求值时,它引发了一个错误.
P.S. python's eval
function does not help in this case. It raised an error, when trying to evaluate with the eval
function.
推荐答案
有时,简化问题要比提出复杂的解决方案更好.您可能希望通过像这样提供代码来简化问题
Sometimes it's better to simplify the question rather than coming up with complicated solutions. You may want to simplify the problem by having your code be provided like this
my_str='I have {6 * (2 + 3)} apples'
这样,您可以使用简单的正则表达式解析它并评估其中的内容.否则,您将面临很多复杂性.
This way you can parse it using a simple regex and eval what's inside. Otherwise you're in for a lot of complexity.
这篇关于Python-评估字符串中的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!