How to assign Print output to a Variable in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
2 min

banner

# Table of Contents

  1. Assign print output to a variable in Python
  2. Redirect print output to a variable in Python

# 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
example = 'bobbyhadz.com' # ๐Ÿ‘‡๏ธ remove call to print() to assign to a variable my_str = str(example) print(my_str) # ๐Ÿ‘‰๏ธ bobbyhadz.com

assign print output to variable

The code for this article is available on GitHub

The 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('bobbyhadz.com') print(my_str) # ๐Ÿ‘‰๏ธ None

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

main.py
example = 'bobbyhadz.com' my_str = example print(my_str) # ๐Ÿ‘‰๏ธ bobbyhadz.com

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)

redirect print output to variable

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev