[Tutor] strings and int()

wesley chun wescpy at gmail.com
Thu Jan 15 08:08:53 CET 2009


> 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.

the reason you get this error is because "2*3" is not a string
representation of an integer whereas "6" is. in other words 2*3 is not
a number.


> How do you take an expression in a string, and evaluate the expression to get a number?

you just said the answer yourself... *evaluate the expression*. to do
just that, use the eval() built-in function. eval("2*3") takes that
string, turns it into Python executable code and returns the
expression that results from the evaluation of that code.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list