How transform str('+') to mathematical operation? For example:
a = [0,1,2] # or a = ['0','1','2']
b = ['+','-','*']
c = int(a[0]+b[0]+a[1])
In other words, how transform str('-1*2')
to int()
, without for i in c: if i == '+': ...
Thanks.
How transform str('+') to mathematical operation? For example:
a = [0,1,2] # or a = ['0','1','2']
b = ['+','-','*']
c = int(a[0]+b[0]+a[1])
In other words, how transform str('-1*2')
to int()
, without for i in c: if i == '+': ...
Thanks.
i thin you're looking for eval(), but i advice to use something else... however,
>>> eval('-1*2')
-2
eval 'executes' the string you pass to it, like code. so it's quite dangerous for security, especially if the parameters are user input...
in this case i suggest to use parsing library, such as ply http://www.dabeaz.com/ply/ that for such thing is really simple to use and very effective :)
Dett,
A Simple eval on the whole string... However be aware that if the user inputs the string, eval is risky, unless you do some parsing first
x = '-1*2'
y = eval(x)
y will then be the integer value.
Use eval like everyone else is saying but filter it first.
>>> s = '1 + 12 / 2 - 12*31'
>>> allowed = set(' 1234567890()+-/*\\')
>>> if allowed.issuperset(s):
... eval(s)
...
-365
You can read about http://en.wikipedia.org/wiki/Reverse_Polish_notation
You can also use the operator module:
import operator as op
#Create a mapping between the string and the operator:
ops = {'+': op.add, '-': op.sub, '*': op.mul}
a = [0,1,2]
b = ['+','-','*']
#use the mapping
c = ops[b[0]](a[0], a[1])
If your math expressions will fit Python syntax but you are skeered of eval (you should be) you can look into python's ast
module (docs). It will parse the expression into an abstract syntax tree you can iterate over. You can evaluate a limited subset of Python and throw errors if you encounter anything outside your expression grammar.