IronPython - Abstract Syntax Tree

Hi,

I would like to convert a string that looks like a list into a real list.

I have found implementation for this by using import ast, however the module is not supported in Rhino 5.

import ast

list = "[1,2,3]"

ast.literal_eval(list)

Can anyone recommend an alternative for this conversion?

You can split text:
http://www.pythonforbeginners.com/dictionary/python-split

And then cast to numbers:

@onrender, list is a python keyword and should never be used as a variable name.

To convert your string which looks like a list to a real list using eval, try this:

A = "[1,2,3]"
print type(A)
B = eval(A)
print type(B)

_
c.

1 Like

Hi onrender

the code below workd in R5:

list_string = "[1,2,3]"
list_object = eval(list_string)
print list_object

Important note: you used list as a variable, but list is a buildin-method, so you overwrote it and can cause unwanted behaviour down the line:

t = (1,2,3) #tuple
t_l = list(t) #make a list from tuple
print 'what is t_l :', t_l

list = 4 #overwrite list
t_l = list(t) #error trying to call an int

-Willem

Thanks.

I tried split however the best is the “eval” because I need to remove the quotation marks and than to recast it again. (Yes, “list” cannot be used as variable.)

Many thanks!

Another way to do this would be to treat the input as a JSON-formatted string:

import json
inp_str = "[1,2,3]"
json.loads(inp_str)

This works mostly like ast.literal_eval, and can deal with strings, numbers, nested lists and dicts, etc.

The potential risks of eval() may or may not be relevant in your situation, but it’s good practice to avoid it anyway.

2 Likes

Thanks I included in the list as well,

More on…Python String Split