Assign print output to a variable in Python

avatar

Borislav Hadzhiev

Last updated: Sep 4, 2022

banner

Photo from Unsplash

Assign print output to a variable in Python #

To assign the output of the print() function to a variable:

  1. Remove the call to the function and assign the argument you passed to print() to the variable.
  2. The print() function converts the provided value to a string, prints it to sys.stdout and returns None.
main.py
from io import StringIO import sys example = 'hello 123' # 👇️ remove call to print() to assign to a variable my_str = str(example) print(my_str) # 👉️ hello 123 # ------------------------------------- # ✅ Redirect print() output to a variable buffer = StringIO() sys.stdout = buffer print('This will be stored in the print_output variable') print_output = buffer.getvalue() # 👇️ restore stdout to default for print() sys.stdout = sys.__stdout__ # 👇️ -> This will be stored in the print_output variable print('->', print_output)

The first example removes the call to the print() function to assign its argument to a variable.

The print function takes one or more objects and prints them to sys.stdout.

Note that the print() function returns None, so don't try to store the result of calling print in a variable.
main.py
# ⛔️ BAD (print always returns None) my_str = print('hello 123') print(my_str) # 👉️ None

Instead, store the value in a variable and pass the variable to the print() function.

main.py
example = 'hello 123' my_str = example print(my_str) # 👉️ hello 123

Alternatively, you can redirect the output of the print() function to a variable.

Redirect print output to a variable in Python #

To redirect the output of the print function to a variable:

  1. Set sys.stdout to an in-memory buffer using the io.StringIO class.
  2. Use the print() function to print a value.
  3. Use the getvalue() method on the object to access the output of the print() function.
main.py
from io import StringIO import sys buffer = StringIO() sys.stdout = buffer print('This will be stored in the print_output variable') print_output = buffer.getvalue() # 👇️ restore stdout to default for print() sys.stdout = sys.__stdout__ # 👇️ -> This will be stored in the print_output variable print('->', print_output)

The io.StringIO class returns an in-memory buffer.

We redirected sys.stdout to the buffer and used the print() function to print a value.

The value can be accessed with the getvalue() method.

The method returns a bytes object that contains the entire contents of the buffer.

After the value is stored in a variable, restore the sys.stdout attribute to the default, so you can use the print() function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.