Mathieu Châteauvert Mathieu Châteauvert -4 years ago 53
Python Question

Python - Whitespace after

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download