Python
Print Function
Programming Tips
Coding Techniques
Output Formatting

How can I print multiple things on the same line, one at a time?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Printing multiple items on the same line incrementally is a common requirement for progress indicators, dynamic status updates, and formatted console output. Most languages append a newline after each print call by default, so you need specific techniques to suppress it. This article covers the primary approaches in Python and briefly touches on how other languages handle the same task.

Using print() with end Parameter

In Python 3, the print() function accepts an end parameter that controls what character is appended after the output. By default it is '\n' (newline). Setting it to an empty string or a space keeps subsequent output on the same line.

python
1# Print items on the same line separated by spaces
2for i in range(5):
3    print(i, end=' ')
4# Output: 0 1 2 3 4
5
6# Print without any separator
7for char in "HELLO":
8    print(char, end='')
9print()  # Add a final newline
10# Output: HELLO
11
12# Custom separator between items
13items = ['apple', 'banana', 'cherry']
14for i, item in enumerate(items):
15    if i > 0:
16        print(', ', end='')
17    print(item, end='')
18print()
19# Output: apple, banana, cherry

Note that you typically want a final print() call at the end to move the cursor to the next line when you are done.

Using sys.stdout.write()

The sys.stdout.write() method gives you lower-level control over output. Unlike print(), it does not append any trailing character automatically, making it ideal for precise formatting.

python
1import sys
2
3# Write without any newline or space
4sys.stdout.write("Loading")
5for _ in range(3):
6    sys.stdout.write(".")
7sys.stdout.write("\n")
8# Output: Loading...
9
10# Writing formatted numbers
11for i in range(1, 6):
12    sys.stdout.write(f"[{i}]")
13sys.stdout.write("\n")
14# Output: [1][2][3][4][5]

One important difference is that sys.stdout.write() only accepts strings, so you must convert other types explicitly with str().

Flushing Output for Real-Time Display

By default, Python buffers stdout when writing to a terminal. This means output may not appear immediately, which is problematic for progress bars and real-time status updates. Use flush=True in print() or call sys.stdout.flush() explicitly.

python
1import time
2
3# Progress bar with flush
4print("Downloading: ", end='', flush=True)
5for i in range(10):
6    time.sleep(0.3)
7    print(f"{'#'}", end='', flush=True)
8print(" Done!")
9# Output builds up: Downloading: ########## Done!
10
11# Using sys.stdout with manual flush
12import sys
13for i in range(5):
14    sys.stdout.write(f"\rProcessing item {i+1}/5...")
15    sys.stdout.flush()
16    time.sleep(0.5)
17print()

Without flushing, the entire output might appear all at once when the buffer fills or the program exits.

Overwriting Lines with Carriage Return

The carriage return character \r moves the cursor back to the beginning of the current line without advancing to a new line. This lets you overwrite previous output, which is useful for progress counters and spinners.

python
1import time
2import sys
3
4# Percentage counter that updates in place
5for i in range(101):
6    print(f"\rProgress: {i}%", end='', flush=True)
7    time.sleep(0.05)
8print()  # Move to next line when done
9
10# Spinner animation
11spinner = ['|', '/', '-', '\\']
12for i in range(20):
13    sys.stdout.write(f"\rWorking {spinner[i % 4]}")
14    sys.stdout.flush()
15    time.sleep(0.2)
16print("\rDone!          ")  # Extra spaces clear leftover characters

When overwriting, make sure the new output is at least as long as the previous output, or pad with spaces to avoid leftover characters.

Using f-strings for Formatted Same-Line Output

Python f-strings combine naturally with the end parameter to produce clean, formatted same-line output.

python
1scores = {'Alice': 95, 'Bob': 87, 'Carol': 92}
2
3# Print a formatted scoreboard on one line
4for name, score in scores.items():
5    print(f"{name}={score}", end='  ')
6print()
7# Output: Alice=95  Bob=87  Carol=92
8
9# Right-aligned progress with f-string formatting
10total = 150
11for step in range(0, total + 1, 30):
12    pct = step / total * 100
13    print(f"\r[{'#' * (step // 5):.<30s}] {pct:5.1f}%", end='', flush=True)

Same-Line Printing in Other Languages

The concept applies across languages, though the syntax varies.

javascript
1// JavaScript (Node.js)
2process.stdout.write("Hello ");
3process.stdout.write("World\n");
4// Output: Hello World
java
1// Java
2System.out.print("Hello ");  // print, not println
3System.out.print("World");
4System.out.println();         // newline at the end
5// Output: Hello World
c
1// C
2#include <stdio.h>
3int main() {
4    printf("Hello ");
5    printf("World\n");
6    // Or use fflush(stdout) for immediate output
7    return 0;
8}

In each case, the key is using the variant of the print function that does not automatically append a newline.

Common Pitfalls

  • Forgetting to flush: Without flush=True or sys.stdout.flush(), buffered output may not appear until the program ends, making progress indicators useless.
  • Leftover characters when overwriting: Using \r to overwrite a longer line with a shorter one leaves trailing characters from the previous output, so always pad with spaces.
  • Missing the final newline: After printing on the same line, forgetting a trailing print() causes the shell prompt to appear on the same line as your output.
  • Using print() in Python 2 syntax: In Python 2, print is a statement, not a function. Writing print("text", end='') in Python 2 prints a tuple instead. Use from __future__ import print_function for compatibility.
  • Mixing print() and sys.stdout.write(): These two methods may buffer independently, causing output to appear in an unexpected order. Stick to one approach within a single output sequence.

Summary

  • Use print(value, end='') in Python 3 to suppress the default newline and keep output on the same line.
  • Use sys.stdout.write() for lower-level control when you want no automatic formatting at all.
  • Always pass flush=True or call sys.stdout.flush() when building real-time progress indicators.
  • Use the carriage return \r to overwrite the current line for counters, spinners, and progress bars.
  • In other languages, use the non-newline print variant such as process.stdout.write() in Node.js, System.out.print() in Java, or printf() in C.

Course illustration
Course illustration

All Rights Reserved.