Python: Assign print output to a variable Python: Assign print output to a variable unix unix

Python: Assign print output to a variable


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 StringIOimport sysresult = StringIO()sys.stdout = resultresult_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 linesmy_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