[Tutor] list to string and string to list
kent37 at tds.net
Fri Apr 17 01:55:10 CEST 2009
On Thu, Apr 16, 2009 at 6:52 PM, johnf <jfabiani at yolo.com> wrote:
> I am dealing with a database field that can only store strings.
> 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.
> newlist= list(mystr)
> I keep thinking there must be a simple way of get this done.
You can use eval() but that is generally discouraged as a security hole.
If the list will just contain integers you can do something ad hoc:
In : mylist=[1,2,3,4]
In : mystr=str(mylist)
In : newlist = map(int, mystr[1:-1].split(','))
In : newlist
Out: [1, 2, 3, 4]
In Python 3 you can use ast.literal_eval().
>>> mylist = [1, 2, 3, 4]
>>> mystr = str(mylist)
>>> import ast
[1, 2, 3, 4]
You can use these recipes:
More information about the Tutor