Why is there a white space that outputs when I print something like this in Python 3?
(Is it in the '\n'
character itself?)
print (my_var1, '\n', my_var_2)
Output :
1
2
I know how to fix it. It is not that complicated, but i was just wondering why...
print
adds a single space (or the value of the sep
keyword argument) after every argument, including `\n'. You might want combine the three strings into a single argument yourself.
print(my_var1 + '\n' + my_var2)
or
print('\n'.join([my_var1, my_var2]))
Better than either of theses would be to use the format
string method:
print('{}\n{}'.format(my_var1, my_var2))
which both handles conversion to str
if necessary and eliminates any temporary objects.
I would prefer, though, setting sep
to \n
as in @billy's answer.
When you have multiple positional arguments in the print
function, it writes the str
form of those arguments with the sep
string between them - which in the default case is one space (' '
). There are many ways to print two variables on two separate lines.
print(my_var1)
print(my_var2)
or
for var in (my_var1, my_var2):
print(var)
or
print(my_var1, my_var2, sep='\n')
or the myriad of other examples here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With