Replace Printed Out Text

How can I replace text that's been printed out on screen already in Java?

That has nothing to do with java actually. Rather you want the console you are displaying in to overwrite the text.

This can be done (in any language) by sending a carriage return (\r in Java) instead of a linefeed (\n in Java). So you never use println(), only print() if you want to do that. If you add a print("\r") before the very first print it should do what you want.

BTW it would be far more elegant and simple if you built the entire time in a string and then output it all at once :)

Replace printed out text

If the output goes to the Terminal then you can use the fact that
\r (Carriage Return) moves the "cursor" to the start of the current
line, without advancing to the next line:

print("10% done ", terminator: "\r")
print("20% done ", terminator: "\r")
print("100% done")

(But note that this does not work in the Xcode debugger console.)

python: replace a printed line's text with another line

You can use \r (carriage return). Also you don't need num as en extra variable to index lst you can use existing i to index lst

import time
lst = ["|","/","-","\\"]
num = 0
for i in range(500):
print(lst[i % 4], end="\r") # i will be between 0 and 3 both inclusive
time.sleep(0.2)

In Python, how to change text after it's printed?

Here's one way to do it.

print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()

You can probably also get clever with ANSI escapes. Something like

sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
time.sleep(1)
sys.stdout.write('\033[D \033[D')
sys.stdout.flush()

How to replace already-printed text in the command prompt?

In most consoles, writing a bare carriage return \r without a newline after it will return the cursor to the beginning of the current line, allowing you to overwrite the existing text. Writing the backspace character \b also moves the cursor back one character.

For simple behavior, such as a progress indicator, this is all you need. For more complex behavior, you need to control the terminal through non-standard means. On Unix-based systems, the ncurses library can be used—it gives you full control over the cursor location, text color, keyboard echoing, more fine-grained keyboard input, and more.

On Windows, there's a suite of functions for manipulating consoles, and they can do mostly the same things as Unix consoles.

Remove and Replace Printed items

Just use CR to go to beginning of the line.

import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)

C - Remove and replace printed items

Use the \b (backspace) character.

printf("Quick brown fox");
int i;
for(i=0; i < 9; i++)
{
printf("\b");
}
printf("green fox\n");

I noticed that putting a \n on the first printf() messed up the output.



Related Topics



Leave a reply



Submit