convert string to list
I have a string of the form, say, '[(1,2),(2,3)]' and want to obtain the list [(1,2),(2,3)] instead.
asked 8 years ago
This post is a wiki. Anyone with karma >750 is welcome to improve it.
I have a string of the form, say, '[(1,2),(2,3)]' and want to obtain the list [(1,2),(2,3)] instead.
You can use the eval
Python function:
sage: s='[(1,2),(2,3)]' ; s
'[(1,2),(2,3)]'
sage: type(s)
<type 'str'>
sage: L = eval(s) ; L
[(1, 2), (2, 3)]
sage: type(L)
<type 'list'>
Note however that the string is not preparsed, so you will get Python ints, note Sage integers:
sage: type(L[0][0])
<type 'int'>
To "benefit" from Sage preparsing, you can do:
sage: L = eval(preparse(s)) ; L
[(1, 2), (2, 3)]
sage: type(L[0][0])
<type 'sage.rings.integer.Integer'>
You may also use the sage_eval
function which does eval(preparse(...))
answered 8 years ago
This post is a wiki. Anyone with karma >750 is welcome to improve it.
Thank you very much for your answer! It works if I use the string s. If instead I use my_string (which, on the surface, looks pretty much like s, but was obtained from opening a .sage file containing the string) then I get: TypeError: 'tuple' object is not callable !!
It works for me when attaching a .sage file with the definition of s. Could you please provide your code ?
Yes, the code looks like this: my file = open(DATA + 'test444.sage') te=myfile.read() te '[(1,2),(2,3),(3,4),(3,5)(3,6),(3,7)]'
You missed a comma between (3,5)
and (3,6)
.
THANK YOU!!!
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 8 years ago
Seen: 2,220 times
Last updated: Jan 04 '17