I have a variable that is function = '(2*1)+3'
. How would I get it out of string form and calculate the answer? I tried using float()
, int(float())
but I'm not sure if that's for numbers only or not.
I've written this a couple times, and every time it seems that I lose the code...
A very simple (and "safe") calculator can be created using ast
:
import ast
import operator
_OP_MAP = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.div,
ast.Invert: operator.neg,
}
class Calc(ast.NodeVisitor):
def visit_BinOp(self, node):
left = self.visit(node.left)
right = self.visit(node.right)
return _OP_MAP[type(node.op)](left, right)
def visit_Num(self, node):
return node.n
def visit_Expr(self, node):
return self.visit(node.value)
@classmethod
def evaluate(cls, expression):
tree = ast.parse(expression)
calc = cls()
return calc.visit(tree.body[0])
print Calc.evaluate('1 + 3 * (2 + 7)')
This calculator supports numbers, addition, subtraction, division, multiplication and negation (e.g. -6
) and parenthesised groups. Order of operations are the same as Python which should be relatively intuitive... It can (almost trivially) be extended to support just about any unary or binary operator that python supports by adding the ast
node type and corresponding operator/function to the _OP_MAP
above.
You may use eval
>>> function = '(2*1)+3'
>>> eval(function)
5
As @mgilson said,
Only do this if you completely trust the source of the string.
I created my own GitHub repository for this:
https://github.com/SubatomicPlanets/StrToMath
It's just one file with about 100 lines and no third-party libraries, and it's pretty simple.
It uses the shunting yard algorithm:
https://en.wikipedia.org/wiki/Shunting_yard_algorithm
Basically, what it's doing is getting a string like "2+4*6"(this is called infix notation) and formatting it into something called postfix notation.
The same expression in postfix looks like this: "246*+"
It is just a different way of writing it.
Calculating postfix is a lot simpler than calculating infix, because there are no parentheses.
In the file I made, I also added a lot of other stuff, like constants, so that you can do this:
Examples:
"what's fifty three+7*6/2?" -> 74
"what is 9 * 67+90?" -> 693
"2^7" -> 128
"-pi+pi" -> 0
"-pi*two" -> -6.283184
"(twenty two*2)+one" -> 45
© 2022 - 2025 — McMap. All rights reserved.
eval
as Avinash suggested or write your own parser – Gapinast.NodeVisitor
, but every time I do it, I lose the code. I should keep it around sometime -- Just for fun. – Ozzie