Home > Blockchain >  How to overwrite a long string print in python?
How to overwrite a long string print in python?

Time:02-21

I know that a similar question has been asked here. The methods work well when the size of the string is not exceeded from a single line. Please consider the following code, which does not have a long string:

import time

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

    time.sleep(0.2)

Now consider the following code. You can see that it just clears the exceeded line not all characters of the printed string. I want the same behavior of the above code.

import time

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

    time.sleep(0.2)

Please note that I use VS code. How can I clear all characters when the size of the string is long?

CodePudding user response:

Maybe you can try this:

import time
import sys

CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'

for x in range(100):
    print(x, "timesjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj")
    sys.stdout.write(CURSOR_UP_ONE*2)
    sys.stdout.write(ERASE_LINE) 
    
    time.sleep(0.2)

And the count of CURSOR_UP_ONE depends on the length of the string and the width of the terminal window.

CodePudding user response:

You can get the terminal size in advance:

from shutil import get_terminal_size


def print_width(s: str):
    tw, th = get_terminal_size((50, 20))

    if len(s) > tw:
        head, tail = s[:tw], s[tw:]
        print(head)
    else:
        print(s)


if __name__ == "__main__":
    my_really_long_str = "timesjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj"

    print_width(my_really_long_str)
  • Related