0

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
1
  • Same output, just no displayed as a tuple (123, 'foo', 456) went to 123 foo 456. Updated original to show what I am trying to get out of it. Commented Aug 4, 2018 at 18:14

2 Answers 2

1

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

This worked for, but saw another follow up after running this. My Var2 is actually a dictionary with two parts, so print(*var4, sep='\n') prints my dictionary list into two lines. Can the * be used to isolate which ones I want to break apart in that manner? I ended up just making a long list of variables and text to get it working for now.
@D-slr8 I'll need a better example inputs & desired outputs to answer that. There are various ways to break up dicts and I don't know which one you want.
all good now, I was able to get something working after some tinkering with the print(*var4, sep='\n')
1

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

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

2 Comments

This returned an error TypeError: sequence item 3: expected str instance, int found. Not sure if this is because I am actually running this print from inside function.
Thanks for pointing that out. I guess you could replace the tuple with a (str(i) for i in var4) to explicitly make each item a type so that it's able to be printed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.