How to redirect print output to a variable in Python

Redirecting print output to a variable assigns the output of a print() statement (standard output) to a variable.

Solution for How to redirect print output to a variable in Python : You can use sys.stdout, io.StringIO, and io.StringIO.getvalue() to redirect print output to a variable Store sys.stdout to a variable. Call io.StringIO() to create a buffer to store standard output. Set sys.stdout to the previous result. Any standard output will now be redirected to the buffer. Call io.StringIO.getvalue() with io.StringIO as the buffer to get the standard output from it.


how-to-redirect-print-output-to-a-variable-in-python