如何使用回车 return 和换行符格式化文本?

How to format text using carriage return and newline?

我想展示这个系列进行实验。

A
B
AA
BB
AAA
BBB

无需添加新行,就像它仅适用于 'A' 一样。 这是仅适用于 A 的代码,并且有效。

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

现在我加了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)

可惜B吃掉了A,只增加了B。我试过这样的东西,但它会导致我不想要的重复

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)

有什么办法可以不重复打印系列吗?我得到了这个作为答案,但似乎很难在 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. 

编辑

curses 和 cololoma 答案都可以,但 curses 导致终端在尝试 except 时死机并且它有点不可配置。 Coloroma 是最简单的,也是我需要的答案。

curses module在这里很有用。

快速演示:

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() 创建一个覆盖整个终端的“window”。 It doesn't have to, though

addstr(y, x, string) 将字符串添加到给定位置。

您可以在文档

中找到更多关于如何 fiddle 和 curses 使其完全按照您的要求行事的更多信息

至于使用 \r 和 \n,我不确定我 运行 是否有办法做到这一点。我通常用于自定义 CLI 输出的是模块 colorama。使用一些控制位,您可以将文本放置在屏幕上任何您想要的位置,甚至可以使用不同的颜色和样式。

网站:https://pypi.org/project/colorama/

代码:

# 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)