[Tutor] list to string and string to list

Martin Walsh mwalsh at mwalsh.org
Fri Apr 17 02:41:01 CEST 2009


johnf wrote:
> 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
>>>> convert
>>>> it back to a list.
>>>>
>>>> But this does NOT work.
>>>> mylist=[1,2,3,4]
>>>> mystr=str(mylist)
>>>>
>>>> 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)
>>>>> s1
>> '1,2,3,4,5'
>>
>>>>> newlist = [int(n) for n in s1.split(',')]
>>>>> newlist
>> [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
are valid.

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)
# '(lp1\nI1\naI2\naI3\naI4\na.'

newlist = pickle.loads(mystr)
# [1, 2, 3, 4]

HTH,
Marty




More information about the Tutor mailing list