Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Assign print output to a variable

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?

like image 570
Willie Koomson Avatar asked May 04 '11 13:05

Willie Koomson


People also ask

How do you assign a print output to a variable in Python?

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 .

Can you assign a variable in a print statement Python?

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.

How do you store output of a print statement 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.


3 Answers

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())
like image 182
Sven Marnach Avatar answered Oct 05 '22 04:10

Sven Marnach


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
like image 28
Arcyno Avatar answered Oct 05 '22 06:10

Arcyno


probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

like image 10
Szymon Lukaszczyk Avatar answered Oct 05 '22 05:10

Szymon Lukaszczyk