Why does \n also make a space?

I’ve written this

print('-'*30,'\nblablablabla\n','-'*30)

But get the output:

------------------------------ 

blablablabla

 ------------------------------

Why is there a space before the last line of dashes?

Hi @ktrager, the \n is the escape character for a newline. So it makes a new line after your string.

By the way: I tested it quickly in a terminal and I don’t have the space. It looks like this on Mac OSX:

$ python3.6 test.py 
------------------------------ 
blablablabla
 ------------------------------

You could also try to write a f-string like this. It’s possible since Python3.6 and it’s very nice:

print(f"{'-'*30}\nblablablabla\n{'-'*30}")

Hi @DidierCH
Thanks for your suggestion - I’ll use your f-string idea in the future.

I think you misunderstood, my question because your output also shows the last line is moved 1 to the right after newline?

Hi @ktrager. Yes I missunderstood you :frowning:

I hadn’t an answer so I warmed up the google engine and found an excellent explanation:

The print function of Python inserts this space as a separator after a comma. Hope it helps.

Thanks for the question, I also learned something new :+1:

Thanks for this @DidierCH, I guess I’ll get around this by using your suggestion:

print(f"{'-'*30}\nblablablabla\n{'-'*30}")

Yes, that’s one way. The other is to use sep="".

print('-'*30,'\nblablablabla\n','-'*30, sep="")

You can also play around with it a little bit, for example you could write this:

print('-'*30,'\nblablablabla\n','-'*30, sep="+")

and you will get this:

------------------------------+
blablablabla
+------------------------------

Keep your attention on the plus-sign. You can use whatever character you want. Even emojis should work:

print('-'*30,'\nblablablabla\n','-'*30, sep="👍")
------------------------------👍
blablablabla
👍------------------------------

That’s where the fun begins …

1 Like

I think you just halted my learning process.
I’ll now be busy making print statements with different emoji combos :wink:
A completely new world has opend

1 Like