# convert string to list

asked 2017-01-03 23:09:51 +0100

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.

edit retag close merge delete

Sort by » oldest newest most voted

answered 2017-01-04 01:10:25 +0100

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 !!

more

It works for me when attaching a .sage file with the definition of s. Could you please provide your code ?

( 2017-01-04 01:21:55 +0100 )edit

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)]'

( 2017-01-04 03:01:38 +0100 )edit

You missed a comma between (3,5) and (3,6).

( 2017-01-04 16:28:36 +0100 )edit

THANK YOU!!!

( 2017-01-04 23:46:42 +0100 )edit

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'>

more

You may also use the sage_eval function which does eval(preparse(...))

( 2017-01-10 15:11:34 +0100 )edit