53

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?

7 Answers 7

36

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())
Sign up to request clarification or add additional context in comments.

6 Comments

That won't work if the value of tag.getArtist() contains non-ascii characters, for example u'Elys\xe9e'. The print statement would display Elysée but str() will throw a UnicodeEncodeError.
@RCross In Python 2, this is indeed true – Unicode strings will be encoded using sys.stdout.encoding when printing them. So you will need to use u'Elys\xe9e'.encode(sys.stdout.encoding) to get the equivalent of what print is doing. In Python 3 you should rarely see this issue, since str in Python 3 is Unicode string type, so str(u'Elys\xe9e') will leave the string unchanged.
OP did not ask how to save a string to another string, but to save the output of a print statement. This answer does not address the question.
@sh37211 It's debatable what exactly the OP asked, and I agree your interpretation is more likely than mine. However, the main purpose of StackOverflow isn't to solve the OP's problem, but to provide a useful resource for people looking for answers to similar problems. It is apparent that for many people this answer solves their problem, so calling this answer "not useful" (by means of a downvote) seems a bit of a stretch.
str(ValueError) does not equal the output of print(ValueError), in the former newlines are escaped.
|
31

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

Comments

13

You can use parameter file to redirect output of print function

from io import StringIO

s = StringIO()
print(42, file=s)
result = s.getvalue()

Comments

9

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

Comments

4
somevar = tag.getArtist()

http://docs.python.org/tutorial/index.html

5 Comments

I believe the OP needs the string representation of the object.
This. Don't take the question too literally. No need for str.
@eumiro: Do you have evidence that the function doesn't return a string?
Do you have evidence that it does return a string? Converting to a string won't hurt. To be honest, I believe your answer is what the OP is looking for anyway :)
There are actually cases when converting to a string will hurt.
1

This is a standalone example showing how to save the output of a user-written function in Python 3:

from io import StringIO
import sys

def print_audio_tagging_result(value):
    print(f"value = {value}")

tag_list = []
for i in range(0,1):
    save_stdout = sys.stdout
    result = StringIO()
    sys.stdout = result
    print_audio_tagging_result(i)
    sys.stdout = save_stdout
    tag_list.append(result.getvalue())
print(tag_list)

Output

['value = 0\n']

Comments

0

You can do this by storing and displaying the object at the same time, look at this example:

with open(f"spaces/{space.meeting_code}.txt", "w") as f:
    print(space, file=f)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.