How to use one print statement but still print on multiple lines
Is there a way that I can only use one print statement but still get the same effect as in the code below? I've tried using end-statements, which either don't work in this situation, or I'm using incorrectly:
print ('Deposit: ' + str(deposit))
print ('Withdrawl: ' + str(withdrawl))
print ('Available amount: ' + str((deposit + withdrawl)//1))
source to share
Yes, you can use \n
to insert a new line:
print('Deposit: {}\nWithdrawl: {}\nAvailable amount: {}'.format(
deposit, withdrawl, (deposit + withdrawl) // 1))
It's not necessarily better. IMHO using separate instructions print()
is more readable here.
You can do it a little better with string concatenation:
print(('Deposit: {}\n' +
'Withdrawl: {}\n' +
'Available amount: {}').format(deposit, withdrawl, (deposit + withdrawl) // 1)
Which, again, isn't necessarily better IMHO.
I also used format
to improve readability; this removed the need for manual calls str
and is more readable (it can do a lot more, see link).
I have tried using end statements which either do not work in this situation, or I am using incorrectly
I assume you used something like print('foo', 'bar', end='\n')
this won't work because it end
only appended to the end of all arguments; the parameter sep
is printed between the arguments (space by default).
So what you want to do is:print('foo', 'bar', sep='\n')
The downside to this is that you need 3 .format
calls or keep your "ugly" string concatenations.
source to share
It looks like you are using Python 3.x. If so, you can set the parameter sep
from print
to '\n'
so that each argument is separated by a newline character
print('Deposit: ' + str(deposit), 'Withdrawl: ' + str(withdrawl), 'Available amount: ' + str((deposit + withdrawl)//1), sep='\n')
It makes you pretty long though. You might want to split it into two lines:
print('Deposit: ' + str(deposit), 'Withdrawl: ' + str(withdrawl),
'Available amount: ' + str((deposit + withdrawl)//1), sep='\n')
Note that you can also just drop multiple newlines at selected locations. This will allow you to write above:
print('Deposit: ', deposit, '\nWithdrawl: ', withdrawl, '\nAvailable amount: ', (deposit + withdrawl)//1)
The best part about this solution is that it gets rid of all calls to str
( print
automatically builds its arguments).
Last but not least, if you are indeed using Python 2.x, then you can import the Python 3.x function print
from __future__
. Place this line at the top of your code:
from __future__ import print_function
source to share