[Tutor] list to string and string to list
mwalsh at mwalsh.org
Fri Apr 17 02:41:01 CEST 2009
> On Thursday 16 April 2009 05:04:39 pm Alan Gauld wrote:
>> "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.
> Kent Johnson suggested
> newlist = map(int, mystr[1:-1].split(','))
Maybe that's a question in disguise, but I would think both suggestions
Another, less valid, suggestion would be to pickle or shelve the list
before storing it in the database -- although this poses similar
security implications as eval. And the resulting string is not
particularly easy to read, if that's important to you.
import cPickle as pickle
mylist = [1,2,3,4]
mystr = pickle.dumps(mylist)
newlist = pickle.loads(mystr)
# [1, 2, 3, 4]
More information about the Tutor