How to format text using carriage return and newline?

Viewed 517

I want to display this series for experimentation.

A
B
AA
BB
AAA
BBB

without adding new line like it works fine with 'A' only. This is code for A only and it works.

root@kali-linux:/tmp# cat a.py 
import time
x = "A"
while True:
    print(x, end = "\r")
    x += "A"
    time.sleep(1)

Now I added B.

root@kali-linux:/tmp# cat a.py 
import time
x = "A"
y = "B"
while True:
    print(x, end = "\r")
    print(y, end = "\r")
    x += "A"
    y += "B"
    time.sleep(1)

Unfortunately B eats the A and only B increases. I tried sth like this but it causes repetition which i dont want

import time
x = "A"
y = "B"
while True:
    print(x, end = "\r")
    print('\n', end='\r')
    print(y, end = "\r")
    x += "A"
    y += "B"
    time.sleep(1)

Is there any way to print the series without repetition? I got this as answer but seems hard to implement in python3.

\r moves back to the beginning of the line, it doesn't move to a new line (for that you need \n). When you have 'A' and 'B' it writes all the 'A's and then overwrites it with the 'B's.
You would need to loop through all the 'A's, then print a new line \n, then loop for the 'B's. 

Edit

Both curses and coloroma answer were OK but curses causes terminal to die when try except and it was slightly inconfigurable. Coloroma was easiest and the answer which I needed.

2 Answers

As far as using \r and \n, I'm not sure that I've run across a way to do this. What I typically use for custom CLI output is the module colorama. Using some control bits, you can position text anywhere you want on the screen, even in different colors and styles.

website: https://pypi.org/project/colorama/

code:

# Imports
import time
import colorama
import os

# Colorama Initialization (required)
colorama.init()

x = "A"
y = "B"

# Clear the screen for text output to be displayed neatly
os.system('cls')  #  For Microsoft Terminal, may be 'clear' for Linux

while True:
    # Position the cursor back to the 1,1 coordinate
    print("\x1b[%d;%dH" % (1, 1), end="")
    # Continue printing
    print(x)
    print(y)
    x += "A"
    y += "B"
    time.sleep(1)

The curses module is useful here.

A quick demo:

import time
import curses

win = curses.initscr()
for i in range(10):
    time.sleep(0.5)
    win.addstr(0, 0, "A" * i)
    win.addstr(1, 0, "B" * i)
    win.refresh()

curses.endwin()

curses.initscr() creates a "window" that covers the entire terminal. It doesn't have to, though

addstr(y, x, string) adds the string to the given location.

You can find a bunch more information on how to fiddle with curses to make it do exactly what you want in the documentation

Related