string to list when the contents is a list

Steven D'Aprano steven at
Thu Feb 18 01:47:20 CET 2010

On Thu, 18 Feb 2010 00:13:05 +0000, Rhodri James wrote:

> On Wed, 17 Feb 2010 23:48:38 -0000, Wes James <comptekki at>
> wrote:
>> I have been trying to create a list form a string.  The string will be
>> a list (this is the contents will look like a list).  i.e. "[]" or
>> "['a','b']"
> If your string is trusted (i.e. goes nowhere near a user), just eval()
> it.

Or use something like YAML or JSON to parse it.

Fredrik Lundh has a simple_eval function which should be safe to use:

But it's fairly simple to parse a simple list like this. Here's a quick 
and dirty version:

def string_to_list(s):
    s = s.strip()
    if not s.startswith('[') and s.endswith(']'):
        raise ValueError
    s = s[1:-1].strip()
    items = [item.strip() for item in s.split(',')]
    for i, item in enumerate(items):
        items[i] = dequote(item)
    return items

def dequote(s):
    for delimiter in ('"""', "'''", '"', "'"):
        if s.startswith(delimiter) and s.endswith(delimiter):
            n = len(delimiter)
            return s[n:-n]
    raise ValueError

>>> s = "['a','b']"
>>> print s
>>> string_to_list(s)
['a', 'b']
>>> x = string_to_list(s)
>>> type(x)
<type 'list'>
>>> x
['a', 'b']


More information about the Python-list mailing list