Home > Enterprise >  Is there a way for a variable to be assigned to the output of a print?
Is there a way for a variable to be assigned to the output of a print?

Time:01-28

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.

CodePudding user response:

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)

CodePudding user response:

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
  •  Tags:  
  • Related