converting lists to strings to lists

bruno at modulix onurb at xiludom.gro
Wed Apr 12 11:22:07 EDT 2006


robin wrote:
> thanks for your answer. split gives me a list of strings, 

Of course, why should it be otherwise ?-)

More seriously : Python doesn't do much automagical conversions. Once
you've got your list of strings, you have to convert'em to floats.

> but i found a
> way to do what i want:
> 
> input='0.1, 0.2, 0.3;\n'
> input = list(eval(input[0:-2]))

- eval() is potentially harmful. Using it on untrusted inputs is a bad
idea. In fact, using eval() (or exec) is a bad idea in most cases.

- removing trailing or leading chars is best done with str.strip()

Also, your code is not as readable as the canonical solution (split() +
float)

> print input
> 
>>[0.10000000000000001, 0.20000000000000001, 0.29999999999999999]

input = map(float, input.strip('\n;').split(","))
[0.10000000000000001, 0.20000000000000001, 0.29999999999999999]

> 
> this does fine... but now, how do i convert this list to a string?
> 
> my_new_string = ' '.join(input)
> 
> gives me:
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: sequence item 0: expected string, float found

Same as above - you need to do the conversion:
' '.join(map(str, input))


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list