[Tutor] string to list

spir denis.spir at free.fr
Wed Feb 10 13:10:55 CET 2010


On Wed, 10 Feb 2010 11:26:25 +0000
Owain Clarke <simbobo at cooptel.net> wrote:

> Please excuse the obviousness of my question (if it is), but I have 
> searched the documentation for how to generate a list e.g. [(1,2), 
> (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point 
> me in the right direction.

Use eval.

Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print eval("[(1,2), (3,4)]")
[(1, 2), (3, 4)]
 
But
-1- This need problem shows a design issue, unless you try this only for exploring python.
-2- One should avoid doing this and using eval() in other circumstances because of security issues: if the code-string comes from external source (data file, network...), there is no way to ensure what it actually does. In a general case, one should _parse_ the text (which probably would not be a python literal, anyway) to _construct_ resulting python data.

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list