Home >Backend Development >Python Tutorial >How Can I Overwrite Previous Output in Python Using `print()`?

How Can I Overwrite Previous Output in Python Using `print()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 16:07:23267browse

How Can I Overwrite Previous Output in Python Using `print()`?

Overwrite Previous Output in Python

In Python, the standard print() function advances the cursor to the next line after displaying the specified text. However, it can be modified to overwrite the previous output on the same line.

Simple Overwrite:

To overwrite the previous line, use the carriage return 'r' character. This returns the cursor to the beginning of the line without advancing it.

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

Line Clearing:

If the new output is shorter than the existing line, the 'x1b[1K' escape sequence should be used.

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

Long Line Wrap:

If the output is longer than a line, disable line wrapping using the 'x1b[7l' escape sequence.

print('\x1b[7l', end='')
for x in range(100):
    print(x, end="\x1b[1K\r")

Re-enable Line Wrap:

Remember to re-enable line wrapping after completing the overwrite operation using the 'x1b[7h' escape sequence.

print('\x1b[7h', end='')

The above is the detailed content of How Can I Overwrite Previous Output in Python Using `print()`?. 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