Welcome to Cadabra Q&A, where you can ask questions and receive answers from other members of the community.
0 votes

After converting a Cadabra expression to a python string (to allow certain manipulations), using the command

str(expr);

I would like to convert back the result to a Cadabra expression and manipulate further.

Is it possible? How could this be done?

related to an answer for: Define python functions
in General questions by (13.2k points)

1 Answer

+1 vote
 
Best answer

All expressions are instances of the Ex class, and you can construct the latter from a string. So you can do e.g.

ex1:= A_{m n} A^{m n};
ex2 = Ex(str(ex1));

after which ex2 is a Cadabra expression with the same content as ex1.

Note that in the second line I used = not :=. This is because we want the Ex(str(ex1)) to be interpreted by Python. Had you written := you would get an expression with the literal content Ex(str(ex1)), not an Ex object constructed from the string representation of ex1.

This may not always work correctly as there are various bugs left in the str method acting on expressions; if you find problems please report them (here or on the github issue tracker).

by (76.7k points)
selected by

Thank you very much @kasper!

...