[Tutor] list to string and string to list

johnf jfabiani at yolo.com
Fri Apr 17 02:16:55 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
> >> 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(','))

-- 
John Fabiani


More information about the Tutor mailing list