Converting from strings to integers

William Tanksley wtanksle at dolphin.openprojects.net
Thu Aug 2 00:03:32 EDT 2001


On 1 Aug 2001 17:49:31 -0700, Stephen Smith wrote:
>Hi, I'm new to Python and am just trying out an example of file I/O. 
>I am trying to read a file (successfully), and then multiply a value
>by another static variable.  The value from the file was outputting in
>the 'string' format, and I need to convert it into an integer.  I
>tried using the int(x) command, but it doesn't seem to care, it is
>still in the string format.

I think I /might/ know what's wrong.  Let me guess: your code looks
something like this:

(incorrect code)
 number = file.readline()
 int(number)
 print number + 3

(Of course, I don't know what you're /actually/ doing; the important thing
is that I'm guessing that you have "int(number)" on a line by itself.)

If this is anything close to true (show me some code if it's not), then
the problem is that "int" isn't a command; it's a function.  int doesn't
change the number you pass to it; it merely produces a number, which you
can then use.  Here's a correct version:

 line = file.readline()
 number = int(line)
 print number + 3

See how I'm using the _result_ of the int function?

Hope this helps.  Sorry if it doesn't; post more code and we'll be able to
help more accurately.

-- 
-William "Billy" Tanksley



More information about the Python-list mailing list