Python: How to Print Without Newline
By Parth Patel on Mar 14, 2020
Python is one of the most easiest language yet most powerful language to learn. Normally, one would start with print "hello world". No, you cannot start learning without that! Never!!
In python, you can print any value using print function. Yes! It's that simple. But there is one interesting problem. In most of the languages, if you want to print something on newline, you have to specifically specify that. Otherwise, it will always print in current line and not move to next/new line.
But, python by default always prints to newline. Now, that might become problem if you actually want to print on same line, isn't it? No worries. Let's see the solutions together.
Since, python has two popular but distinct versions ~ Python 2.x and Python 3.x, let's look into the solutions separately.
Print without newline in Python 3
1) Using print function
In python 3, you can print multiple times without newline by simply overriding end parameter in the print function. Basically, by default Python appends newline to print function but you can override it with empty string and it won't print to newline.
Let's see one example:
print("Hello World", end="") print(" Again!")
Hello World Again!)
Let's try one more different example. We will use loop to print multiple integers separated by "." (and not newline ). Here, we are using end parameter to append "." at the end of print statement.
# python print on same line separated by "." for i in range(1,10): print(i, end='.')
2) Using "sys" Library
Okay. Honestly, I cannot think of any situation where you would prefer this over print function, but let's explore this solution at least for fun. You can import and use sys library in python 3 to print strings or variables in same line avoiding newline.
#Import the inbuilt sys library import sys #First Line of output sys.stdout.write("Hello World") #Second Line of output sys.stdout.write(" Again!")
Print without newline in Python 2
1) Using print function
In python2, you can use print statement (yes, print is not a function rather a statement in python 2.x) with comma to prevent newline.
Let's see example:
print "Hello World", print " Again!"
This is how you can print without newline in python 3 using end argument and python 2 using comma. I hope you find it useful. Let me know in comments how you are using this trick.