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: [geeks,neveropen] Output: geeks neveropen Input: a = [1, 2, 3, 4] Output: 1 2 3 4
Python3
print ( "geeks" ) print ( "neveropen" ) |
Output
geeks
neveropen
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 # geeks and neveropen # in the same line # Without newline print ( "geeks" ), print ( "neveropen" ) # Array a = [ 1 , 2 , 3 , 4 ] # Printing each element on the same line for i in xrange ( 4 ): print (a[i]), |
geeks neveropen 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 # geeks and neveropen # in the same line print ( "geeks" , end = " " ) print ( "neveropen" ) # array a = [ 1 , 2 , 3 , 4 ] # printing a element in same # line for i in range ( 4 ): print (a[i], end = " " ) |
geeks neveropen 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) |
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( "Lazyroar " ) sys.stdout.write( "is best website for coding!" ) |
Lazyroar is best website for coding!