How to print without newline in Python?

Generally, people switching from C/C++ to Python wonder how to print two or more variables or statements without going into a new line in python. Since the Python print() function by default ends with a newline. Python has a predefined format if you use print(a_variable) then it will go to the next line automatically.

Example

Input: [Beginner,w3wiki]
Output: Beginner w3wiki

Input: a = [1, 2, 3, 4]
Output: 1 2 3 4  

Python3




print("Beginner")
print("w3wiki")


Output

Beginner
w3wiki

But sometimes it may happen that we don’t want to go to the next line but want to print on the same line. So what we can do? The solution discussed here is totally dependent on the Python version you are using. 

Print without newline in Python 2.x

In Python 2.x, the print statement does not have the end parameter like in Python 3.x. To achieve the same behavior of printing without a newline in Python 2. x, you can use a comma at the end of the print statement, just like in the given code.

Python




# Python 2 code for printing
# on the same line printing
# Beginner and w3wiki
# in the same line
 
# Without newline
print("Beginner"),
print("w3wiki")
 
# Array
a = [1, 2, 3, 4]
 
# Printing each element on the same line
for i in xrange(4):
    print(a[i]),


Output

Beginner w3wiki
1 2 3 4


Print without newline in Python 3.x

In Python 3.x, the print() function behaves slightly differently from Python 2.x. To print without a newline in Python 3. x, you can use the end parameter of the print() function.

python3




# Python 3 code for printing
# on the same line printing
# Beginner and w3wiki
# in the same line
 
print("Beginner", end =" ")
print("w3wiki")
 
# array
a = [1, 2, 3, 4]
 
# printing a element in same
# line
for i in range(4):
    print(a[i], end =" ")


Output

Beginner w3wiki
1 2 3 4 


Print without newline in Python 3.x without using For Loop

In Python 3. x, you can print without a newline without using a for loop by using the sep parameter of the print() function. The sep parameter specifies the separator to be used between multiple items when they are printed.

Python3




# Print without newline in Python 3.x without using for loop
 
l = [1, 2, 3, 4, 5, 6]
 
# using * symbol prints the list
# elements in a single line
print(*l)


Output

1 2 3 4 5 6


Print without newline Using Python sys module

To use the sys module, first, import the module sys using the import keyword. Then, make use of the stdout.write() method available inside the sys module, to print your strings. It only works with string If you pass a number or a list, you will get a TypeError.

Python3




import sys
 
sys.stdout.write("w3wiki ")
sys.stdout.write("is best website for coding!")


Output

w3wiki is best website for coding!