[Tutor] RE: I don't understand why it doesn't work :(

Alan Gauld alan.gauld@blueyonder.co.uk
Tue Jun 3 17:57:02 2003


> I expected 17 because I tought that
> print int (s) convert my string in an integer
> so that the addition between 3*4 and 5 was possible.

But "3*4" is not a number it is an arithmetic expression.
YOu could evaluate the string and then add 5:

result = eval("3*4") + 5

But int() expects the string representation of 
a number and only a number.

If you know the format of the string you could also
do:

result = int(s[0]) * int(s[-1) + 5

which converts the first and last characters of s to ints.

Or you could split the expression using the arithmetic 
operators (+-*/) as the dividing characters and try to 
interpret the string that way (but then that's what 
eval() does for you!)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld