Convert a string to a list

Nick Craig-Wood nick at craig-wood.com
Tue Apr 24 19:30:03 CEST 2007


rh0dium <steven.klass at gmail.com> wrote:
>  I am using pexpect to drive another tool.  Some of the data I get back
>  would be better suited as a list and I want to know a simple way to
>  parse the data to push it into a list.
> 
>  For example
> 
>  I get the following string back.  I want to convert this to a list:
> 
>  '("." ".." "cdslib_cleanup.py" "cadence.py"
>  "cdsinit_cdsenv_cleanup.py")'
> 
>  should be:
>  ["." ".." "cdslib_cleanup.py" "cadence.py"
>  "cdsinit_cdsenv_cleanup.py"]
> 
>  It should be able to handle embeded lists like this:
>  '("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py"
>  "cdsinit_cdsenv_cleanup.py")'
> 
>  should become
>  ["." ["cadence.py" "foo_cleanup.py"] "cdslib_cleanup.py" "cadence.py"
>  "cdsinit_cdsenv_cleanup.py"]

Here is a cheap, nasty and insecure solution

>>> a='("." ".." "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")'
>>> eval(a.replace('" "', '", "').replace('" (', '", (').replace(') "', '), "'))
('.', '..', 'cdslib_cleanup.py', 'cadence.py', 'cdsinit_cdsenv_cleanup.py')
>>> b='("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")'
>>> eval(b.replace('" "', '", "').replace('" (', '", (').replace(') "', '), "'))
('.', ('cadence.py', 'foo_cleanup.py'), 'cdslib_cleanup.py', 'cadence.py', 'cdsinit_cdsenv_cleanup.py')
>>>

It made tuples rather than lists but I expect that won't matter.

Someone normally chimes in with pyparsing at this point...

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list