converting lists to strings to lists

Dave Hansen iddw at hotmail.com
Wed Apr 12 12:58:10 EDT 2006


On 12 Apr 2006 06:53:23 -0700 in comp.lang.python, "robin"
<robin.meier at gmail.com> wrote:

>hi,
>
>i'm doing some udp stuff and receive strings of the form '0.870000
>0.250000 0.790000;\n'
>what i'd need though is a list of the form [0.870000 0.250000 0.790000]
>i got to the [0:-3] part to obtain a string '0.870000 0.250000
>0.790000' but i can't find a way to convert this into a list. i tried
>eval() but this gives me the following error:
>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "<string>", line 1
>    .870000 0.250000 0.79000
>
>and i have the same problem the other way round. e.g. i have a list
>which i need to convert to a string in order to send it via udp.
>btw: i cannot use pickle, since i'm sending stuff to a LISP programme.
>

Here's a little playing around I did the the interactive interpreter.
Not guaranteed to be the most efficient or Pythonic, but it seems to
work...

>>> instr = '0.870000 0.250000 0.790000;\n'
>>> instr
'0.870000 0.250000 0.790000;\n'
>>> ell = [float(x) for x in instr[:-2].split()]
>>> print ell
[0.87, 0.25, 0.79000000000000004]
>>> outstr = " ".join(["%8.6f"%x for x in ell]) + ";\n"
>>> outstr
'0.870000 0.250000 0.790000;\n'
>>> instr == outstr
True

Regards,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list