On Thu, Jan 15, 2009 at 1:14 AM, Mr Gerard Kelly <s4027...@student.uq.edu.au> wrote: > If you have a string "6", and you do int("6"), you get the number 6. > > But if you have a string "2*3" and you do int("2*3") you get a name error. > > How do you take an expression in a string, and evaluate the expression > to get a number? > > I want to be able to turn the string "2*3" into the number 6.
There is a method for that, namely eval. eval("2*3") evaluates 2*3 as a Python expression and thus gives the integer 6. However, usage of eval is very much discouraged, because it is a very unsafe function. The problem is that a Python expression can be formed to do whatever Python can, and that's a lot. If you use it on something coming from outside the program, you open up your program to an attack by providing malevolent data. If you use it on something from inside your program, it is usually is better to look more precisely on what you are creating. Still, I guess it could be used provided that you _first_ check whether the string is of a form that does not have anything dangerous coming from it. In your case, you might execute eval only if the string that it is to be executed on consists only of numbers and the characters -+/*%(). I _think_ there is nothing bad that can happen then. -- André Engels, andreeng...@gmail.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor