string to list when the contents is a list
Tim Chase
python.list at tim.thechases.com
Thu Feb 18 10:18:57 EST 2010
Wes James 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']"
>
> The "[]" is simple since I can just check if value == "[]" then return []
>
> But with "['a','b']" I have tried and get:
>
> a="['a','b']"
>
> b=a[1:-1].split(',')
>
> returns
>
> [ " 'a' "," 'b' " ]
>
> when I want it to return ['a','b'].
Just to add to the list of solutions I've seen, letting the
built-in csv module do the heavy lifting:
>>> s = "['a','b']"
>>> import csv
>>> no_brackets = s[1:-1] # s.strip(' \t[]')
>>> c = csv.reader([no_brackets], quotechar="'")
>>> c.next()
['a', 'b']
This also gives you a bit of control regarding how escaping is
done, and other knobs & dials to twiddle if you need.
Additionally, if you have more than one string to process coming
from an iterable source (such as a file), you can just pass that
iterator to csv.reader() instead of concocting a one-element list.
-tkc
More information about the Python-list
mailing list