D-slr8
D-slr8

Reputation: 109

Variable with other variables always prints to same line python

Why does a variable holding other variables print to just one line, even with explicitly listing sep and end?

var1 = 123
var2 = ("foo", "678)
var3 = 456
var4 = var1, var2, var3
print(var4)   # Or sep="\n"   Or end="\n"
print("var1 is ", var1, var2, var3)

Results either which way I seem to run this is:

(123, 'foo', 456)
123 foo 456

*Update - Ican do a work around like this, but callign on this multiple times is redundant.

print("var1 is: ", var1,
  "\nvar2 is: ", var2,
  "\nvar3 is: ", var3)
# Results were
var1 is:  123 
var2 is:  foo 
var3 is:  456

Without being able to store the new lines into a variable, I have to relist this method at every point, which is redundant. Using

print(*var4, sep='\n')

Breaks apart var2 (which is actually a dict on my script), resulting in output like:

123
foo
1
foo
2
var3

Upvotes: 0

Views: 69

Answers (2)

N Chauhan
N Chauhan

Reputation: 3515

Not sure what you're asking, but you could always do...

print('\n'.join(var4))

Upvotes: 1

gilch
gilch

Reputation: 11681

Try

print(*var4, sep='\n')

This will unpack the tuple, so print gets them as multiple arguments instead of as a single tuple argument. (This way it can actually use the separator.)

Upvotes: 1

Related Questions