aidanmelen
aidanmelen

Reputation: 6594

python use carriage return to re-write multiple lines

Let's say I had a list of multi-line strings:

l = [
"""hello
world""",
"""this
is
a
multiline
string""",
"""foo
bar"""
]

for s in l:
    print(s)

hello
world
this
is
a
multiline
string
foo
bar

instead of printing a newline after each multiline string, I would like to print each element in the list where each iteration we will carriage return back to the begin such that the multiline string reprints over the last.

How can this be achieved in python3?

Upvotes: 3

Views: 2059

Answers (1)

Sergey Nudnov
Sergey Nudnov

Reputation: 1429

You could use ANSI sequences and colorama module to make them working under Windows too.

This code is tested on Linux (bash) and Windows (CMD and PowerShell) consoles:

from __future__ import print_function
import colorama

colorama.init()

# ESC [ n A       # move cursor n lines up
# ESC [ n B       # move cursor n lines down
cursor_up = lambda lines: '\x1b[{0}A'.format(lines)
cursor_down = lambda lines: '\x1b[{0}B'.format(lines)

l = [
"""hello
world""",
"""this
is
a
multiline
string""",
"""foo
bar"""
]

max_lines = 0

for s in l:
    print(s)

    # count lines to reach the starting line
    lines_up = s.count('\n')+2

    # save maximum value
    if lines_up > max_lines:
        max_lines = lines_up

    # going up to the starting line
    print(cursor_up(lines_up))

# going down to ensure all output is preserved
print(cursor_down(max_lines))

Results:

>python test.py
fooso
barld
a
multiline
string
>

Upvotes: 3

Related Questions