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

How Can I Overwrite Previous Output in Python's `print()` Function?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 07:47:09603browse

How Can I Overwrite Previous Output in Python's `print()` Function?

Overwriting Previous Output on Stdout

In Python, the default behavior of the print() function is to start a new line after each invocation. However, certain scenarios require overwriting the previous output on the same line.

Simple Overwrite

To overwrite the previous line, append 'r' (carriage return) to the end argument of print(). This return character moves the cursor to the beginning of the current line without starting a new one.

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

Line Cleaning

When the new text is shorter than the previous line, it may leave remnants of the old text. To clear any remaining characters, append 'x1b[1K' (clear to end of line) to the end argument.

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

Long Line Wrap

Line wrapping refers to the automatic continuation of a line past its end-of-line. To prevent line wrapping and force successive characters to overwrite existing ones, disable line wrapping using 'x1b[7l' and re-enable it using 'x1b[7h'.

print('\x1b[7l', end='')  # disable line wrap
print('\x1b[7h', end='')  # re-enable line wrap

Note: Line wrap re-enabling must be done manually to prevent terminal breakage. Additionally, these solutions only control the length of the current line and do not overflow to subsequent lines.

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