Ask Your Question

Converting strings into expressions

asked 2018-02-15 13:02:49 -0500

trenzafeeds gravatar image

updated 2018-02-21 07:25:09 -0500

Hey everyone, This is probably pretty straightforward, but I couldn't find any straightforward answers with google searching. I'm looking for a function that works in the same way as python's str() and float() functions, but turns variables (especially strings) into sage's different classes of variables, like expressions. For example, if I have string variable: expression = "x1^2*x2*x3*4" and x1, x2, and x3 are already declared as variables, how can I turn that variable into a sage expression so it will work with things like the coefficient() function? Thanks!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-02-15 16:29:36 -0500

slelievre gravatar image

updated 2018-02-15 16:32:42 -0500

To convert a string expression to any parent X in Sage, you could do X(expression).

Thus, to convert the expression to Sage's symbolic ring, use SR(expression).

Here is how it would work with your example.

sage: x1, x2, x3 = SR.var('x1 x2 x3')
sage: expression = "x1^2*x2*x3*4" 
sage: ex = SR(expression)
sage: ex

If you prefer to work with a polynomial ring:

sage: P.<x1, x2, x3> = QQ[]
sage: f = P(expression)
sage: f
edit flag offensive delete link more


Thank you! This worked perfect for me

trenzafeeds gravatar imagetrenzafeeds ( 2018-02-20 14:40:46 -0500 )edit

is it possible to convert a string of inequality to a sage expression?

nimaous gravatar imagenimaous ( 2018-11-02 10:19:54 -0500 )edit

@nimaous: good question. I suggest asking a new question for that.

slelievre gravatar imageslelievre ( 2018-11-02 18:55:16 -0500 )edit

Well, but this does no work for the following case. I want to define an equation from a string, by changing the value of gammaWStr='9.81' by a string that is a number.

gammaW - gammaWStr == 0

If I follow the suggested construction like

exprString = 'gammaW - ' + gammaWStr + ' == 0'
eq0 = SR(exprString)

I get the Error Message

TypeError: Malformed expression: gammaW - 9.81 == !!!  0

In other words, and referring to the first question, How about an expression like expression = "x1^2*x2*x3*4==0"?

loSuarezB gravatar imageloSuarezB ( 2018-11-20 10:18:50 -0500 )edit

Thanks for reporting. This is now tracked at Sage Trac ticket 26727: Make SR('x == 0') work.

slelievre gravatar imageslelievre ( 2018-11-20 12:03:54 -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

1 follower


Asked: 2018-02-15 13:02:49 -0500

Seen: 1,177 times

Last updated: Nov 20 '18