python string question

JTsyo

Lifer
Nov 18, 2007
12,068
1,159
126
If I had a string that was 'a[0][0]'. Is there a way to convert this so that I can use it as an index?
 

Dimmu

Senior member
Jun 24, 2005
890
0
0
I don't know of a built in python function that does exactly what you want (~parse to enum), but there are some solutions. For examples, look at this page. Other than that you could run that string through some regular expressions to first determine if the string contains valid syntax, then check to see if 'a[0][0]', etc, is a valid call (invalid/valid for any number of reasons), then execute the extrapolated command if it is.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Try 'a[0][0]'.split("[]")[1] and 'a[0][0]'.split("[]")[2]... e.g. something like

a[ 'a[0][0]'.split("[]")[1] ] [ 'a[0][0]'.split("[]")[2] ]

Maybe you need to do some integerization. Every time I write a python script I relearn the bloody language.
 

Dimmu

Senior member
Jun 24, 2005
890
0
0
Not sure why I didn't think of this sooner, but you can use the exec() function to do, to the best of my knowledge, exactly what you want. For example, "exec('print a[0][0]')", will print a[0][0] to the screen. Assuming of course that a list 'a' exists and the element at '[0][0]' supports indexing and printing, etc. Just replace the print command with whatever it is that you need to do. Much easier, eh?

EDIT: Here's a link to the exec() documentation.
 

JTsyo

Lifer
Nov 18, 2007
12,068
1,159
126
Originally posted by: Dimmu
Not sure why I didn't think of this sooner, but you can use the exec() function to do, to the best of my knowledge, exactly what you want. For example, "exec('print a[0][0]')", will print a[0][0] to the screen. Assuming of course that a list 'a' exists and the element at '[0][0]' supports indexing and printing, etc. Just replace the print command with whatever it is that you need to do. Much easier, eh?

EDIT: Here's a link to the exec() documentation.

Thanks!
 

Dimmu

Senior member
Jun 24, 2005
890
0
0
Originally posted by: JTsyo
Thanks!

Yup! Happy to help.

Originally posted by: degibson
exec ftw.

Pretty much that. :D It's been quite a while since I've used Python, but still, I'm surprised I forgot about the awesomeness that is exec().