How to convert string to list without eval or exec

Paul McGuire bogus at bogus.net
Tue Mar 9 04:16:59 EST 2004


"Oliver Kurz" <olku at web.de> wrote in message
news:mailman.158.1078818680.19534.python-list at python.org...
> Hello,
>
> could someone give me a solution how to convert a string to a list without
using eval or exec?
>
> The string looks like:
>
>
'[["abc","abc",["abc","abc"],"abc"],["abc","abc",["abc","abc"],["abc",["abc"
,"abc"]],"abc"],"abc"]'
>
> and should be converted to a list:
>
> [['abc', 'abc', ['abc', 'abc'], 'abc'], ['abc', 'abc', ['abc', 'abc'],
['abc', ['abc', 'abc']], 'abc'], 'abc']
>
> I'm not allowed to use eval or exec.
>
> -- 
> --
> Oliver Kurz
>
>
# get pyparsing at http://pyparsing.sourceforge.net

from pyparsing import quotedString, Forward, Literal,delimitedList,Group
quotedString.setParseAction(lambda s,l,t: t[0].strip("'\""))

testdata =
'[["abc","abc",["abc","abc"],"abc"],["abc","abc",["abc","abc"],["abc",["abc"
,"abc"]],"abc"],"abc"]'

lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
listDef = Forward()

# add more things to listItem, such as integers, etc. if your list has other
than quoted strings
listItem = quotedString | listDef

listDef << lbrack + Group( delimitedList(listItem) ) + rbrack

print listDef.parseString(testdata)[0].asList()





More information about the Python-list mailing list