In this post, we will see how to print without Newline in Python.
In python, when you use two print statements consecutively, it will print in different line.
1 2 3 4 |
print('Hello world') print('from Java2blog') |
Output:
from Java2blog
As expected, we got Hello world
and from Java2blog
If you want to print these two print statements in the same line, you can do it in different ways.
💡 Did you know?
If you are using python 2, then you can simply put comma(
,
) to print statements in same line.
12345 #print without new line but with spaceprint('Hello world'),print('from Java2blog')
Using print statement
You can use end='$delimiter'
with print statements and it will print string with delimiter.
Print with space
You can use end=' '
for printing statements separated by space.
1 2 3 4 |
print('Hello world',end=' ') print('from Java2blog') |
Output:
Print with comma(,)
You can use end=','
for printing statements separated by comma.
1 2 3 4 |
print('Hello world',end=',') print('from Java2blog') |
Output:
Using sys library
You can also import sys
library and use sys.stdout.write()
to print on same line.
1 2 3 4 5 |
import sys sys.stdout.write('Hello world') sys.stdout.write(' from Java2blog') |
Output:
Printing without newline is very useful while printing using a loop. If you don’t want to print each element in an individual line, you can use end=' '
with print statement to print on the same line.
1 2 3 4 5 |
countryList =["India","China","Russia","France"] for country in countryList: print(country,end=' ') |
Output:
As you can see, all the elements are printed on same line separated by space(' '
)
That’s all about Python Print without Newline.