Ask Your Question
1

convert string to list

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

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-04 00:50:00 +0100

tmonteil gravatar image

updated 2017-01-04 00:52:50 +0100

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 15:11:34 +0100 )edit
0

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

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

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

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

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

THANK YOU!!!

Sillaw gravatar imageSillaw ( 2017-01-04 23:46:42 +0100 )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 23:09:51 +0100

Seen: 2,073 times

Last updated: Jan 04 '17