'Is there a way for a variable to be assigned to the output of a print?
I'm pretty new to python, and I was wondering if I could assign the output of a print function to a variable (so not a = print('b'), but something like a = (the print output of printing b)). I couldn't find much on my own.
#I have a list of variables assigned to text
thelist = ('abdf')
h = print(*thelist, sep=" ", end=" ")
j = str(print(*thelist, sep=" ", end=" "))
print(j)
Here's the closest I have right now.
Solution 1:[1]
print does not expose the string it constructs from its arguments. You need to do that explicitly:
j = ' '.join(thelist) + ' '
That is,
print(*args, sep=x, end=y)
can be thought of as shorthand for
t = x.join(args) + y
print(t)
Solution 2:[2]
You can redirect the print() function's output to something file-like by specifying a file= keyword argument, such as a StringIO variable:
from io import StringIO
a, b, d, f = 1, 2, 'foo', 42
var_list = a, b, d, f
buffer = StringIO()
print(*var_list, sep=" ", end=" ", file=buffer)
print(buffer.getvalue()) # -> 1 2 foo 42
You could also do the same thing with the contextlib.redirect_stdout() function as show below. It might be the better choice if you were going to do make multiple separate calls to print within the block.
from contextlib import redirect_stdout
a, b, d, f = 1, 2, 'foo', 42
var_list = a, b, d, f
buffer = StringIO()
with redirect_stdout(buffer):
print(*var_list, sep=" ", end=" ")
print(buffer.getvalue()) # -> 1 2 foo 42
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
| Solution 2 |
