Last updated: Apr 9, 2024
Reading timeยท2 min

To assign the output of the print() function to a variable:
print() to the variable.print() function converts the provided value to a string, prints it to
sys.stdout and returns None.example = 'bobbyhadz.com' # ๐๏ธ remove call to print() to assign to a variable my_str = str(example) print(my_str) # ๐๏ธ bobbyhadz.com

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.
print() function returns None, so don't try to store the result of calling print in a variable.# โ๏ธ 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.
example = 'bobbyhadz.com' my_str = example print(my_str) # ๐๏ธ bobbyhadz.com
Alternatively, you can redirect the output of the print() function to a
variable.
To redirect the output of the print function to a variable:
sys.stdout to an in-memory buffer using the io.StringIO class.print() function to print a value.getvalue() method on the object to access the output of the
print() function.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.
You can learn more about the related topics by checking out the following tutorials: