What Does [end=""] means python?

Question:

So I have been solving this problem on HackerRank and got stuck thinking about how to print the output of the problem on the same line. After that, I gave up and looked up the answer on the internet. Even though it worked all confused about how and why.

https://www.hackerrank.com/challenges/python-print/problem?isFullScreen=true

here is the Link of the Problem

I did reach this point and got stuck:

n = int(input())
for i in range(1, n+1):
    print(i)

The output should be 123…n.

My Output was
1
2
3
.
.
.
n(every number on a new line)

The output should be in the same line.
So here is the required soln to the problem

n = int(input())
for i in range(1, n+1):
    print(i, end="")

Can Anyone explain how it works? How did this , end="" changed the whole solution

Asked By: Virat Srivastava

||

Answers:

It means do not start a new line at the end of the print

By default, Python puts a newline character at the end of a print statement.

If you want, instead, to keep the output cursor on the same line, so you can print something afterwards, use end="". The next print statement will continue outputting on the same line.

print("Hello, ")
print("World!")

gives you

Hello,
World!

But

print("Hello, ", end="")
print("World!")

gives you

Hello, World!

Here is my evidence.

enter image description here

Answered By: Eureka

python adds a n’ (newline) character after each string if you use the print function. With the named argument end you can provide a custom last character, or a string, instead of ‘n’. So if end="" there will be nothing added to the end resulting in everything printed on the same line.

Answered By: Casper Kuethe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.