Home > Net >  Printing and replacing multiple lines
Printing and replacing multiple lines

Time:07-14

I have a list with some numbers, for example:

list = [0, 1, 2, 3, 4]

And need my output to be:

0
1
2

And then replace the output in the terminal to be:

1
2
3

And so on. I tried using print() with \r key to replace, but since i need to print multiple lines, it doesn't replace, and i get the following as an output:

0
1
2
1
2
3
2
3
4

I think i need something to limit the amount of lines shown, but i can't make it work.

CodePudding user response:

If your terminal supports it, you can use the VT100 escape sequence <ESC>[{COUNT}A, for example:

n = 3
move_cursor_vt100 = f'\x1b[{n 1}A'

L = [0, 1, 2, 3, 4]

for i in range(len(L)-n 1):
    if i != 0:
        print(move_cursor_vt100)
    sub = L[i:i n]
    for x in sub:
        print(x)

Although, this doesn't clear the lines. So if you were to have L = [90, 1, 2, 3, 4], the first line would be 90, then 10, then 20. You can use <ESC>[2K to clear a line.

CodePudding user response:

import os
os.system('cls||clear')

I used cls||clear because it may vary across platforms like @Imjohns3 said

  • Related