Ask Your Question
1

convert string to list

asked 2017-01-03 16:09:51 -0500

this post is marked as community wiki

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 flag offensive close merge delete

2 answers

Sort by » oldest newest most voted
1

answered 2017-01-03 17:50:00 -0500

tmonteil gravatar image

updated 2017-01-03 17:52:50 -0500

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'>
edit flag offensive delete link more

Comments

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

Sébastien gravatar imageSébastien ( 2017-01-10 08:11:34 -0500 )edit
0

answered 2017-01-03 18:10:25 -0500

this post is marked as community wiki

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

edit flag offensive delete link more

Comments

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

tmonteil gravatar imagetmonteil ( 2017-01-03 18:21:55 -0500 )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)]'

Sillaw gravatar imageSillaw ( 2017-01-03 20:01:38 -0500 )edit

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

tmonteil gravatar imagetmonteil ( 2017-01-04 09:28:36 -0500 )edit

THANK YOU!!!

Sillaw gravatar imageSillaw ( 2017-01-04 16:46:42 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2017-01-03 16:09:51 -0500

Seen: 110 times

Last updated: Jan 03