When I started learning python, finding out how to print without a newline in python was one of the first things that came up.
In C/C++, it was easy to continuously print multiple variables or statements without starting a new line. There is a little trick (syntax) in python (version 3) to print on the same line.
Today, we’ll have a look at different techniques on how to print without a CR with python.
This tutorial is divided into two sections based on the python versions.
If you are using an older version, I recommend updating your python to unlock more features.
How to Print on The Same Line Using Python 3.X
#1 Method – Using the end
in The Print Function
In python 3.x version, you can use the parameter end
to specify what you want at the end of a printed string.
Without the end
parameter, the python adds a '\n'
(line feed) as the default value to the end of the message.
For instance, if you execute more than one print()
function (as shown below) then you get the following output:
Code:
print("The count is:")
for count in range(10) :
print(count)
Output:
The count is:
0
1
2
3
4
5
6
7
8
9
If you want to print multiple variables in a continuous line, you need to set a value for the end
parameter. This value can be anything even ""
(blank space). Refer to the sample program below:
Code:
print("The count is:", end=" ")
for count in range(10):
print(count,end=" ")
Output:
The count is: 0 1 2 3 4 5 6 7 8 9
Besides the end
parameter, you can also use the sep
parameter. sep
is used when we want to publish multiple objects, and we want to insert a specific element after each printed value.
sep
parameter comes handy when you want to insert in-between string values multiple times.
Sep
is mostly used to create CSV files, because it allows the user to distinguish between multiple values.
Code:
val = "The count"
for count in range(4) :
print(val,count, sep=" is: ")
Output:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
Sometimes when we have a requirement where results need to be shown simultaneously while code continues to run. For such cases, we implement the flush
parameter in the print()
function.
The print()
function puts all the values in an internal buffer, and whenever it detects a "\n"
, all the values will be printed on the screen.
We use a custom-valued end, you will see some delays in the output. To print the output as the execution takes place, I recommend using the flush
parameter. Flush will clear the buffer each time the print()
function is executed.
Code:
import time
print("Sending", end=" ")
def Greetings(message):
i=0
print("wait",end=' ')
for item in message:
i = i+1
time.sleep(1)
print(item, end='.', flush=True)
Li = ["Hello","How","are","you","?"]
Greetings(Li)
print("Done")
Output:
Sending wait Hello.How.are.you.?.Done
Note: We have created the function “Greetings” above to see how flush
works
#2 Method – Using “Sys” Library
This particular method works for both python 3.x and 2.x versions. Here, we use the sys
library and stdout.write()
function to print values instead of default print function.
sys.stdout.write()
function will not end with a new line until it is asked to. So that makes it possible to print words without starting a new line.
Code:
import sys
sys.stdout.write("Hello there!")
sys.stdout.write("It is a great day.")
Output:
Hello there!It is a great day.
How to Print a List in Python Without A New Line?
Generally, if you are printing a list whole together, that will be printed on a single line. Still, if you are willing to write each element using a loop or under specific conditions, you can use the end
parameter to avoid entering a new line.
Code:
l1 = [1,2,3,4,5,6,7,8,9]
index = len(l1)
i = 0
while (i< index):
print(l1[i],end="")
i = i+1
Output:
123456789
Is there Printf()
(From C) Equivalent In Python
There is not a similar function in python for printf()
, but with some little tweaks in print()
function, you can achieve the same functionality.
We can use modulo operation (%)
in the print()
function to print formatted outputs similar to printf()
function.
Code:
l1 = [1,2,3,4,5,6,7,8,9]
index = len(l1)
i = 0
while i< index:
print("% 2d" %l1[i], end=" ")
i = i+1
Output:
1 2 3 4 5 6 7 8 9
How to print on the Same Line using Python 2.6, 2.7
#1 Method – Using Comma ,
In Print()
Function
Python 2.x is an older version, and print function is different than the latest version. To print on the same line, you can implement a comma ,
in the print function.
Even if you are using multiple print statements, comma ,
will help you print all the outputs on the same line.
Code:
print 'Print', 'without Newline'
Output:
Print without Newline
#2 Method – Import Print()
for Version 2.6 Or 2.7
In python 2.6 or later versions, you can import libraries of future releases and can use them in your current version. To import libraries from newer versions, you can use the __future__
module.
Generally, the __future__
module serves three different purposes, you can read them here. But we will be using it to import libraries from python 3 version.
Code:
from __future__ import print_function
print("Hey there!", end=' ')
print("How are you?")
Output:
Hey there! How are you?
#3 Method – Use “sys.stdout.write()”
We have already discussed the use of sys
while talking about the python version 3 methods. Since sys.stdout.write()
works the same way in V2, we won’t go into the details once more here.
Using a comma ,
will output a space between two printed strings. The sys.stdout.write()
can be especially useful for V2 if you want to control the added space at the end of print statement.
Let’s see how it works.
Code
import sys
# Two spaces exist between two sentences
print ("I don't want a space at the end."), (" Since I will add one")
# No extra space exists between two sentences here
sys.stdout.write("Look, no space has been added here!")
sys.stdout.write(" It is a great start.")
Output
I don't want a space at the end. Since I will add one
Look, no space has been added here! It is a great start.
Printing A-List Without a Newline or Space
You can use the sys.stdout.write
, or alternatively, you can make the print
function available to the current scope by using the __future__
statement.
Let’s first try by importing the print from Python 3.
Code:
from __future__ import print_function
for i in range(10):
print(i, end="")
Output
0123456789
So we printed on the same line and also eliminated the space with the above example.
Note: Keep in mind that the flush
parameter is not available for print
function in Python 2.
And now we test the sys.stdout.write
below.
Code:
import sys
for i in xrange(10):
sys.stdout.write(str(i))
Output
0123456789
Final Words
Today we’ve learned different ways of printing multiple values on a single line.
Let’s summarize all methods available to print without a new line flush for Python 3 and Python 2.6 in a table.
Python 3.x | Python 2.6, 2.7 | |
---|---|---|
Printing without a newline |
|
|
Printing without a newline and space |
|
|
Python is a modern programming language, and unlike traditional languages, it is designed with various customization options available.
In the first place, python seems like a strict language, but when you look deeper into the function definitions, you will find that there are dozens of options available to perform a single action.
Save this post on pinterest for reference