mix up between numbers and strings

Greg Landrum glandrum at my-deja.com
Wed Sep 6 10:04:53 EDT 2000


In article <x%et5.130$me.274476 at nnrp5.proxad.net>,
  "Jad Courbage" <jad at altern.org> wrote:
> Hi,
>
> I wrote a program to extract data from a file (with help of
> narray=file.readlines()).
> The problem is that it seems that the interpreter "thinks" that
narray is a
> string array
> although the file it is extracted from is a number data file.
Therefore, I
> can't manipulate my data as numbers.
> Sorry for this newbieish question
> Any idea ?
>

As the previous posters have said, you are getting an array of strings
because that's what readlines() returns.  If you know that your data
only contain integers, you could do:
narray = map(lambda x: int(x),file.readlines())
Of course, this will fail the moment you have a line which isn't a
number; even a blank line will kill it.  A more robust solution
would be something like:

narray = []
lines = file.readlines()
for line in lines:
    try:
        narray.append(int(line))
    except:
        pass

Hope this helps,
-greg


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list