Print in one line dynamically
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Dynamic single-line printing in Python means updating text on the same console line instead of printing a new line each time. This is commonly used for progress bars, countdown timers, loading spinners, and download indicators. Python's print() function supports this through the end and flush parameters, and the \r carriage return character moves the cursor back to the beginning of the line so the next print overwrites the previous output.
Using print() with end and flush
By default, print() appends a newline (\n) and Python buffers stdout. Setting end="" removes the newline, \r returns the cursor to the start of the line, and flush=True ensures the text appears immediately.
Progress Bar Example
This creates a visual progress bar that updates in place. The print() at the end ensures the cursor moves to a new line after the bar reaches 100%.
Using sys.stdout.write
sys.stdout.write() gives lower-level control. Unlike print(), it does not add a newline or spaces, so you manage formatting entirely. Call sys.stdout.flush() explicitly to push buffered output to the terminal.
Printing Multiple Values on One Line
Overwriting Longer Lines with Shorter Text
When a shorter string replaces a longer one, leftover characters from the previous output remain visible. Use string formatting like {msg:<30} to pad the output with spaces, ensuring the entire previous line is overwritten.
ANSI Escape Codes for Advanced Control
\033[2K is an ANSI escape code that clears the current line. This is more robust than padding with spaces and works in most modern terminals.
Common Pitfalls
- Forgetting
flush=True: Python buffers stdout by default. Withoutflush=True, the output may not appear until the buffer fills or a newline is printed, making the dynamic update invisible until the loop finishes. - Not using
\rto return the cursor: Usingend=""alone appends text to the same line without overwriting. You need\rat the start of the string to move the cursor back to the beginning so subsequent prints replace the previous text. - Shorter text leaving residual characters: If the new output is shorter than the previous one, old characters remain on screen. Pad the output with spaces (e.g.,
f"\r{msg:<40}") or use ANSI clear-line codes to prevent visual artifacts. - Using
print()in Jupyter notebooks or IDEs: Some environments like Jupyter notebooks do not support\rproperly. In Jupyter, useIPython.display.clear_output(wait=True)ordisplay()with update for dynamic output. - Mixing
print()withsys.stdout.write(): Both write to stdout but handle buffering and newlines differently. Mixing them can cause output ordering issues. Stick to one approach within a given output sequence.
Summary
- Use
print(text, end="", flush=True)with\rto overwrite the current line dynamically \rmoves the cursor to the start of the line;end=""prevents a newline;flush=Trueforces immediate outputsys.stdout.write()provides lower-level control without automatic newlines- Pad shorter output with spaces or use ANSI escape codes to clear residual characters
- Use
print(items, end=" ")or", ".join(list)to print multiple values on one line - In Jupyter notebooks, use
clear_output(wait=True)instead of\r
Related reading
- Print list without brackets in a single row
- Print very long string in Pandas dataframe
- Printing Lists as Tabular Data
- Printing optional variable
- Printing Python version in output
- Probability distribution in Python
- Problem with running object_detection_tutorial TypeError load missing 2 required positional arguments
- Problems using MySQL with AWS Lambda in Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.