开发者

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 wor开发者_如何学JAVAds, how transform str('-1*2') to int(), without for i in c: if i == '+': ... Thanks.


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


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


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.


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


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


Use eval:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜