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
Release: 2024-12-06 16:07:23
Original
292 people have browsed it

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")
Copy after login

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")
Copy after login

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")
Copy after login

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='')
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template