What does end=' ' in a print call exactly do?

python, python-3.x

Solution

Check the reference page of `print`. By default there is a newline character appended to the item being printed (`end='\n'`), and `end=''` is used to make it printed on the same line.

And `print()` prints an empty newline, which is necessary to keep on printing on the next line.

EDITED: added an example. Actually you could also use this:

def a(n):
    print('*' * n)
    for i in range(n - 2):
        print('*' + ' ' * (n - 2) + '*')
    if n > 1:
        print('*' * n) 

Problem

I'm struggling to understand this exercise: ``` def a(n): for i in range(n): for j in range(n): if i == 0 or i == n-1 or j == 0 or j == n-1: print('*',end='') else: print(' ',end='') print() ``` which prints an empty square. I thought I could use the code ``` print("*", ''*(n-2),"*") ``` to print the units in between the upper and the lower side of the square but they won't be aligned to the upper/lower side ones, which doesn't happen if you run the first code. So, could this be because of `end=''` or `print()`? Would you be so kind and tell me what do they mean?

Original source

Related problems