Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 381
Mathieu Châteauvert Avatar asked Dec 08 '22 18:12

Mathieu Châteauvert


2 Answers

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.

like image 154
chepner Avatar answered Jan 05 '23 17:01

chepner


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.

like image 24
Billy Avatar answered Jan 05 '23 19:01

Billy