# How to convert a python string into cadabra expression?

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

+1 vote

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 (65.1k points)
selected by

Thank you very much @kasper!