Home >Backend Development >Python Tutorial >How Can I Overwrite Previous Print Outputs on the Same Line in Python?

How Can I Overwrite Previous Print Outputs on the Same Line in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 18:20:11361browse

How Can I Overwrite Previous Print Outputs on the Same Line in Python?

Overriding Previous Print Outputs on the Same Line

In programming, it's common to encounter situations where you need to update an existing value displayed on the standard output (stdout) without adding a newline. Consider the following Python code:

for x in range(10):
    print(x)

This code outputs the numbers 1 to 10 on separate lines. To overwrite the previous value and replace it with the new value on the same line, you can utilize the following techniques:

Simple Version:

Utilize the carriage return ('r') character to return to the beginning of the line without advancing to the next line.

Python 3:

for x in range(10):
    print(x, end='\r')
print()

Python 2.7 Forward Compatible:

from __future__ import print_function
for x in range(10):
    print(x, end='\r')
print()

Python 2.7:

for x in range(10):
    print '{}\r'.format(x),
print

Python 2.0-2.6:

for x in range(10):
    print '{0}\r'.format(x),
print

In these examples, the trailing comma after the print statement suppresses the newline. The final print statement advances to the next line, ensuring that your prompt doesn't overwrite your output.

Line Cleaning:

If you cannot guarantee that the new line of text is not shorter than the existing line, you can employ the "clear to end of line" escape sequence 'x1b[1K' ('x1b' = ESC):

for x in range(75):
    print('*' * (75 - x), x, end='\x1b[1K\r')
print()

Long Line Wrap:

The aforementioned methods assume that you're not writing beyond the line length. The carriage return only returns to the beginning of the current line. Therefore, if your output exceeds the line length, you'll only erase the last line.

To mitigate this issue and prevent the cursor from wrapping to the next line, you can disable line wrapping:

print('\x1b[7l', end='')    # Disable line wrapping
print('\x1b[7h', end='')    # Re-enable line wrapping

Please note that you must manually re-enable line wrapping at the end of the code block to avoid leaving the terminal in a broken state.

The above is the detailed content of How Can I Overwrite Previous Print Outputs on the Same Line in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn