[Tutor] list to string and string to list
alan.gauld at btinternet.com
Fri Apr 17 02:04:39 CEST 2009
"johnf" <jfabiani at yolo.com> wrote
>> I want to save the list to the field and when I retrieve the string
>> it back to a list.
>> But this does NOT work.
>> newlist= list(mystr)
>> I keep thinking there must be a simple way of get this done.
> Is this a good way?
> newlist = eval(mystr)
eval has all sorts of security implications so I wouldn't recommend
it where you are reading data fropm an external source.
One thing that might work is this:
>>> L = [1,2,3,4,5]
>>> s1 = ','.join(str(n) for n in L)
>>> newlist = [int(n) for n in s1.split(',')]
[1, 2, 3, 4, 5]
Provided your original data doesn't have commas to start with
it should work, I think... And the data needs to be pretty
homogenous to allow a single conversion function.
Author of the Learn to Program web site
More information about the Tutor