Pass end="" to the built-in print() function (print("text", end="")) to suppress the default trailing newline, and pass sep="" (print("a", "b", sep="", end="")) when printing multiple arguments to eliminate the default space separator between items.
Basic Example
# 1. Suppress trailing newline using end=""
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Output: Loading...
# 2. Suppress spaces between multiple arguments using sep=""
print("2026", "11", "26", sep="-", end="")
print(" | Ready")
# Output: 2026-11-26 | Ready
Key Details & Edge Cases
- Output buffering when
end=""has no newline (flush=True): Standard output (sys.stdout) is typically line-buffered in terminals—meaning Python holds characters in memory until a\nis printed or the program exits. When building progress indicators, spinners, or countdowns on a single line, passflush=Trueso text appears immediately:import time for i in range(1, 4): print(f"\rProgress: {i * 33}%", end="", flush=True) time.sleep(0.5) print() # Print a final newline when finished - Overwriting the current terminal line (
\rcarriage return): Combineend="\r"(or start the string with"\r") withend=""andflush=Trueto update status text in place on the same console line without scrolling. - Direct stream writing (
sys.stdout.write()): For raw, unformatted output with zero automatic spaces or newlines,sys.stdout.write("text")writes strings directly to standard output (and returns the character count written), requiring manualstr()conversion for non-strings andsys.stdout.flush()if immediate rendering is needed. - Joining items cleanly before printing: When printing elements of an iterable without spaces or newlines,
print("".join(str(x) for x in items), end="")avoids loop overhead and writes the entire sequence in one call.
Comparison of print() Formatting Arguments & Alternatives
| Approach | Syntax | Trailing Character | Item Separator | Best Used When |
|---|---|---|---|---|
Default print() |
print("a", "b") |
"\n" (newline) |
" " (single space) |
Standard line-by-line console output. |
| No trailing newline | print("a", end="") |
"" (none) |
" " (single space) |
Appending text onto the same line across multiple calls. |
| No newline & no space | print("a", "b", sep="", end="") |
"" (none) |
"" (none) |
Concatenating multiple values inline without formatting gaps. |
| Live single-line update | print("\rStatus", end="", flush=True) |
"" (none, flushed) |
" " (single space) |
Progress bars, timers, and real-time terminal counters. |
sys.stdout.write() |
sys.stdout.write("a") |
"" (none) |
N/A (single str only) |
Low-level stream I/O where print() formatting isn’t needed. |
You must log in or register to comment.
