2010/2/18 Wes James <compte...@gmail.com>: > 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']. > > How can I do this? > > thx, > > -wes > -- > http://mail.python.org/mailman/listinfo/python-list >
The potentially problematic exec or eval options left aside, if you really need to do this, you might consider pyparsing; check the example http://pyparsing.wikispaces.com/file/view/parsePythonValue.py If you know, the input string will always have this exact format (single quoted comma separated one-character strings between square brackets), you might use regular expressions to some extent, e.g. print re.findall(r"(?<=')\w(?=')", "['a','b','c','b','A']") ['a', 'b', 'c', 'b', 'A'] hth, vbr -- http://mail.python.org/mailman/listinfo/python-list