Brian Blais wrote: > I have a string input from the user, and want to parse it to a > number, and would like to know how to do it. I would like to be able > to accept arithmetic operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad > security problems (not that it's a big deal in my app, but still...)
eval() is the preferred way unless you have serious security reasons: >>> def calc(s): ... try: ... return float(eval(s, dict(__builtins__=None))) ... except Exception, e: ... raise ValueError, "error during expression evaluation: %s" % e ... >>> calc("3**4") 81.0 >>> calc("58+34*4") 194.0 >>> calc("58+34*4+a") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 5, in calc ValueError: error during expression evaluation: name 'a' is not defined >>> calc("object.__class__") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 5, in calc ValueError: error during expression evaluation: name 'object' is not defined >>> calc("3.__class__") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 5, in calc ValueError: error during expression evaluation: unexpected EOF while parsing (line 1) >>> calc("type(3).__class__") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 5, in calc ValueError: error during expression evaluation: name 'type' is not defined Of course, one can still bring your system to its knees when "1000**1000000000000000"... -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list