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

Magnus Lyckå magnus@thinkware.se
Tue Jun 3 08:52:02 2003


 >>> print int.__doc__
int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.

 >>>

Converting a string to a number is not the same as to evaluate
a mathematical expression. To evaluate a string as an expression
and return the result as for instance an int, you can use eval()
instead.

Strings fed to int must really be integers in the given base.
int('1010', 2), int('55') and int('beef', 16) will all work, but
not even int('5.3') is accepted, since integers don't have fractions.
int(5.3) will be trunctated and converted from float ti int, but
strings must be proper integers.

 >>> print eval('3 * 4') + 5
17

Note that eval can do all sorts of things.

 >>> password = "secret"
 >>> eval("password + ' '")*5
'secret secret secret secret secret '

In other words, you should be careful in evaluating strings that
for instance come through a web form. They might contain expressions
that disturb your program or reveal secrets.

BTW, there is something wrong with your return address. Mail to
<willblake@wanadoo.fr> bounces.

At 14:25 2003-06-03 +0200, Guillaume wrote:
>Hi,
>My problem is quite simple.
>Here is the prog:
>  s = "3 * 4"
>print type (s)
><type 'str'>
>
>Easy but then I tried:
>print int (s) + 5
>I was waiting for something like 17
>but it doesn't work :(
>Why?
>This is my only question.
>Thanx

--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language