converting lists to strings to lists

Peter Hansen peter at engcorp.com
Wed Apr 12 10:49:14 EDT 2006


robin wrote:
> 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

Actually, that's already a bug.  You want [0:-2] if you're going to do 
it that way.  Unless you meant that your string actually has a backslash 
and an "n" character, which is doubtful...

You should probably use something more like Steven's solution, although 
I'd personally use s.strip(';') or at least s.rstrip(';') if I had 
semicolons to remove, rather than a combined endswith(';') and slicing 
the last character off.

> 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

(If you'd posted the full error (that's an incomplete traceback), 
someone would probably have pointed out how to interpret what Python 
told you so that you'd already have figured out what was wrong with that...)

-Peter




More information about the Python-list mailing list