Monday, January 26, 2015

Evaluating Strings

As I have been working on my Material IO addon I realized that I would have to convert strings to back to their original, built-in types. I thought I was going to manually have to code this, but I came across this built-in function ast.literal_eval(string) which does it all for you.

You can give it a string like "[1, (4, 5, 6), 2, (0.5, 0.4, 0.5)]" and it will convert all of it to an actual list that can be indexed.

Example:

1
2
3
4
5
6
import ast
a = "[1, 2, (3, 4, 5)]"
print(type(a))
b = ast.literal_eval(a)
print(type(b))
print(b[2][2])

Output:

1
2
3
<class 'str'>
<class 'list'>
5



No comments:

Post a Comment