string to list? possible?

Mark McEahern marklists at mceahern.com
Sun Jan 20 14:59:57 EST 2002


maximilianscherr wrote:
> i need to convert a string like "[1, 2, 3, 4]" to a list [1, 2, 3, 4].
> possible?

There are probably better ways than the following, but it works:

$ python
Python 2.2 (#1, Dec 31 2001, 15:21:18)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "[1, 2, 3, 4]"
>>> s = s.replace("[", "")
>>> s
'1, 2, 3, 4]'
>>> s = s.replace("]", "")
>>> s
'1, 2, 3, 4'
>>> l = s.split(",")
>>> l
['1', ' 2', ' 3', ' 4']
>>> for x in range(len(l)):
...     l[x] = int(l[x])
...
>>> l
[1, 2, 3, 4]

Cheers,

// mark




More information about the Python-list mailing list