Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does end=' ' exactly do?

So, I'm struggling trying to understand this kinda simple 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 tought 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?)?

like image 571
Pldx Avatar asked Dec 04 '13 10:12

Pldx


People also ask

What does end =' do in Python?

The end parameter in the print function is used to add any string. At the end of the output of the print statement in python. By default, the print function ends with a newline. Passing the whitespace to the end parameter (end=' ') indicates that the end character has to be identified by whitespace and not a newline.

What is the purpose of end?

The purpose of end is to append a string at the end of a print(). Appending a string to another string can also be accomplished by the “+” operator which is also known as the concatenation operator.

What is the use of end operator?

An end operator represents the end of a sequence of operators or of a control flow. The use of end operators is optional. If you do not place an end operator in your control flow, the system adds one when the control flow is run.


2 Answers

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) 
like image 158
starrify Avatar answered Sep 30 '22 15:09

starrify


In Python 3.x, the end=' ' is used to place a space after the displayed string instead of a newline.

please refer this for a further explanation.

like image 30
Nilani Algiriyage Avatar answered Sep 30 '22 15:09

Nilani Algiriyage