dett
dett

Reputation: 83

Python. Transform str('+') to mathematical operation

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.

Upvotes: 1

Views: 951

Answers (7)

Bill Gribble
Bill Gribble

Reputation: 1797

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.

Upvotes: 2

Sacha
Sacha

Reputation: 3888

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])

Upvotes: 4

aaronasterling
aaronasterling

Reputation: 71054

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

Upvotes: 1

Ant
Ant

Reputation: 5424

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 :)

Upvotes: 2

Dmytro Krasun
Dmytro Krasun

Reputation: 1742

You can read about http://en.wikipedia.org/wiki/Reverse_Polish_notation

Upvotes: 1

Mark Ellul
Mark Ellul

Reputation: 1906

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.

Upvotes: 0

Stompchicken
Stompchicken

Reputation: 15961

Use eval:

> eval(str('-1*2'))
> -2

Upvotes: 0

Related Questions