Print Without Newline in Python

  1. Print Without the Newline in Python Using the end Parameter in the print() Function
  2. Print Without the Newline in Python Using the sys.stdout.write() Function

This tutorial will demonstrate various methods to print the text without a newline in Python. The print() function in Python 2 and 3, adds the newline at the end of the input text each time it is called. This tutorial will explain how we can print the text in the same line with and without a space in Python 2 and 3.

The print(object(s), sep, end) function in Python 3, takes one or more object as input, converts it into the string, and then prints it. The sep parameter (default value ' ' ) represents the separator used by the print() function to separate the input objects if multiple objects are provided. The end parameter (default value \n) represents the value the print() function prints at the end of the last object.

To print the text without the newline, we can pass an empty string as the end argument to the print() function. Similarly, we can pass the empty string as the sep argument if we do not want a space between each object.

The example code below demonstrates how to print without a newline using the print() function in Python 3:

print('Hello',end='', sep='')
print(' ',end='', sep='')
print('Hello',end='', sep='')

Output:

Hello Hello
Note

For Python 2, we need to import the print_function from the future module to use the above code.

Example code:

from __future__ import print_function

print('Hello',end='', sep='')
print(' ',end='', sep='')
print('Hello',end='', sep='')

Output:

Hello Hello

The sys.stdout.write() function prints the text provided as input on the screen. It does put the newline \n at the end of the text.

Therefore, to print the text without the newline in Python, we can pass the text to the sys.stdout.write() function as shown in the below example code:

import sys

sys.stdout.write('Hello')
sys.stdout.write(' ')
sys.stdout.write('Hello')

Output:

Hello Hello
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Print

  • Print Values Without Spaces in Between in Python
  • Print Tab in Python