In Python, the print()
function is used for displaying output on the screen. By default, print() method adds a new line character (\n
) at the end of the printed output on the screen. That is why all print()
statements display the output in a new line on the screen.
While this behavior is suitable for most situations, there are times when we want to avoid those line feeds and print content on the same line.
1. Default Behavior
Let’s start by understanding the default behavior of print()
method. We print two strings using print() in two statements.
print("Hello")
print("World")
We can verify in the output that each print()
statement creates a new line, which is the standard behavior.
Hello
World
end
‘ Parameter
2. Print without New Line using ‘We can use the end
parameter of the print()
function to specify what character should be used at the end of each printed line.
By default, end
is set to '\n'
, but we can change it to an empty string ''
to avoid the line feed.
print("Hello", end='')
print("World")
Program output.
HelloWorld
As shown above, by setting end
to an empty string, the two print()
statements are concatenated on the same line without a space or line feed between them.
3. Print Without New Line in Python 2
In Python 2, printing objects on the same line is rather easy. We just need to add a comma (','
) character between the two print()
statements.
print "Hello",
print "World"
Program output.
Hello World
4. Python Example of Printing on Same Line
Printing on the same line is necessary in multiple usecases. For example, when running long tasks or loops, we can print progress indicators on the same line to provide real-time feedback to users:
import time
for i in range(10):
print(f"Progress: {i}% complete", end='\r') # `\r` moves the cursor to the beginning of the line
time.sleep(1)
In this example, the prograss count happens in the same line and place similar to what we see in software installation wizards.
Happy Learning !!
Comments