Reading in strings -> numbers ??

chris_barker at chris_barker at
Sat Apr 29 03:32:22 CEST 2000

Well, the partner to file.write is What you are really
looking for is a partner to '%f %f'%(3,4), which is essentially an
sprintf(). So, what you want is an sscanf() or fscanf(). I've been
looking for that for a while. What I would like is a version like the
one in MATLAB, that gives you a whole matrix in one swipe.

Unfortunatly, it doesn't exist for python. Someone did make a Python
sscanf module, but I never got around to compiling it. there is also a
tablio (or something like that) module around. In the mean time, you can
always use something like:

list = map(float,string.split(file.readline)))

or, to use your example:

>>> map(float,string.split((" %e %e %d" % (1.2, -3.5, 10))))
[1.2, -3.5, 10.0]

it doesn't work if you want mixed types, but it gets you by.


> Louis M. Pecora <pecora at> wrote in message
> news:<280420001700308281%pecora at>...
> > Is there a Python "read-partner" for the write(string) function,
> >
> > fileobject.write(" %e %e %d" % (1.2, -3.5, 10))
> >
> > in the sense that the C functions fprintf and fscanf are partners.
> >
> > I've looked in 4 different Python books and in the pdf references,
> > I see nothing in read or readlines or strings that seems to make for
> > easy conversion from a string to a list or tuple of objects
> > In other words, I want the opposite of the write above so I can read
> > those numbers back into my Python code.

Sent via
Before you buy.

More information about the Python-list mailing list