I would like to know how to assign the output of the print
function (or any function) to a variable. To give an example:
import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
How do I assign the output of print tag.getArtist
to a variable?
So print() also a function with the return value with None . So the return value of python function is None . But you can call the function(with parenthesis ()) and save the return value in this way. So the var variable has the return value of some_function() or the default value None .
The print statement can be used to print variables, strings, and the other data types provided in Python. We can print different data types in Python's single statement by separating the data types or variables with the , symbol. We will show different methods to print a variable in Python.
Using closure, you can save the print statement and its parameter at the time it called. Then you can call this saved statement at any time you want later.
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
probably you need one of str
,repr
or unicode
functions
somevar = str(tag.getArtist())
depending which python shell are you using
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With