How to undo a string and calculate
Question: > **Possible Duplicate:**  
>  [parsing math expression in python and solving to find an
> answer](http://stackoverflow.com/questions/13055884/parsing-math-expression-
> in-python-and-solving-to-find-an-answer)

How can I "undo" a string with plus and addition signs in order to calculate
them?

I have a string for example:

> '6*1+7*1+1*7'

I tried int() but I've got error. How can I undo this whole string to just get
a pure integer calculation?


Answer: You have to actually implement the operations you want to support by parsing
the string and calculating the result. A trivial parser would look like:

    
    
    >>> import functools,operator
    >>> sum(functools.reduce(operator.mul, map(int, summand.split('*')), 1)
    ...     for summand in '6*1+7*1+1*7'.split('+'))
    20
    

Note that the built-in
[`eval`](http://docs.python.org/3/library/functions.html#eval) may work in a
one-off script or an interactive console, but it interprets the string as
Python source and therefore allows anyone who controls the string (i.e. the
user) to [execute arbitrary Python
commands](http://en.wikipedia.org/wiki/Arbitrary_code_execution).

