| Store | Cart

How to convert string to list without eval or exec

From: Paul McGuire <bog...@bogus.net>
Tue, 09 Mar 2004 09:16:59 GMT
"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:>>
>> 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 =

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()

Recent Messages in this Thread
Paul McGuire Mar 09, 2004 09:16 am
Peter Otten Mar 09, 2004 09:54 am
William Park Mar 09, 2004 04:59 pm
DomF Mar 10, 2004 12:02 pm
Peter Otten Mar 10, 2004 12:57 pm
Peter Harris Mar 11, 2004 10:28 pm
Messages in this thread