49

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?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Willie Koomson
  • 499
  • 1
  • 4
  • 3

7 Answers7

35

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())
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 4
    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 Dec 07 '18 at 13:29
  • 2
    @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. – Sven Marnach Dec 07 '18 at 14:02
  • 2
    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 Feb 25 '21 at 01:24
  • 1
    @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. – Sven Marnach Feb 25 '21 at 09:24
  • str(ValueError) does not equal the output of print(ValueError), in the former newlines are escaped. – run_the_race Jun 15 '22 at 12:49
  • @run_the_race `str(some_error)` does not output anything at all – it just converts `some_error` to a string using its `__str__()` method. If you enter `str(some_error)` in the interactive interpreter, the inrerpreter will show the representation of the string, i.e. `repr(str(some_error))`. So to get a useful comparison, you either need to compare `print(some_error)` with `print(str(some_error))`, and you will see they are the same. In other words, the output of `print(some_error)` function matches the string returned by `str(some_error)`. – Sven Marnach Jun 15 '22 at 12:59
29

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
Arcyno
  • 4,153
  • 3
  • 34
  • 52
9

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

Szymon Lukaszczyk
  • 712
  • 1
  • 6
  • 14
9

You can use parameter file to redirect output of print function

from io import StringIO

s = StringIO()
print(42, file=s)
result = s.getvalue()
sluki
  • 524
  • 5
  • 15
4
somevar = tag.getArtist()

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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']
-1

In Python 3.x, you can assign print() statement to the variable like this:

>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>

According to the documentation,

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). 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.

>>> var = some_function()

So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

So we get a string object, then you can modify the below code line as follows,

>>> var = str(some_function())

or you can use str.join() if you really have a string object.

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

change can be as follows,

>>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58