Here are two ways to print without a newline in Python.
- Using print()
- Using stdout.write()
Method 1: Using print()
By default, print() function adds a newline character (\n) at the end of the output.
However, you can change this behavior by setting the end parameter to an empty string (””) or any other character/string of your choice.
Visual Representation
Example 1: Basic Usage
Output
Example 2: For loop
# Loop through numbers from 0 to 4 and print them on the same line separated by spaces
for i in range(5):
print(i, end=" ")
Output
0 1 2 3 4
Method 2: Using stdout.write()
The stdout.write() method in the sys module does not add a newline character at the end of the output, unlike the print() function.
Visual Representation
Example
import sys
# Writing a string to stdout without a newline
sys.stdout.write("First part,")
# Subsequent output will continue on the same line
sys.stdout.write(" and here's the second part.")
Output
First part, and here's the second part.
That’s it.