Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one get string conversion in sympy to behave as pretty print?

Tags:

python

sympy

I wanted to be able to get the str conversion function in python to act as the pretty print function in sympy (or print as if init_printing() was called with any argument(s)). Right now if one calls such a function it only changes the print function that prints to the screen. How do I get str to behave as pprint or other options? In short it would be awesome to be able to get/intercept the output of print somehow in a string and a variable in python itself.

For example I want to be able to do:

from sympy import *
x,y=symbols('x y')
x_eq_y = Eq(x,2*y)
x_eq_y_str = str(x_eq_y) # holds 'Eq(x,2*y)' but I want it to hold 'x = 2y' or a latex formula etc

is it possible to do that?

like image 204
Charlie Parker Avatar asked Jan 30 '26 12:01

Charlie Parker


1 Answers

str is just one of printing functions available in SymPy. If you want to use another one, use it:

x_eq_y_str = latex(x_eq_y)  # get  'x = 2 y' 
x_eq_y_str = pprint(x_eq_y)  # get  x = 2⋅y 
x_eq_y_str = pprint(x_eq_y,  use_unicode=False)  # get  x = 2*y

Edit:

Using sympy 1.4 the pprint function does not return the string. This should work instead:

    x_eq_y_str = pretty(x_eq_y)  # get  x = 2⋅y 
    x_eq_y_str = pretty(x_eq_y,  use_unicode=False)  # get  x = 2*y

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!