【问题标题】:How to format text using carriage return and newline?如何使用回车符和换行符格式化文本?
【发布时间】:2021-01-02 01:42:00
【问题描述】:

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

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 和 coloroma 的答案都可以,但是 curses 在尝试时会导致终端死亡,但它有点无法配置。 Coloroma 是最简单的,也是我需要的答案。

【问题讨论】:

  • 我已经根据您的编辑更新了答案。

标签: python python-3.x formatting newline carriage-return


【解决方案1】:

就使用 \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)

【讨论】:

  • 啊,原来是这样的!我记得几年前使用了一个不同的模块,它比 curses 更容易用于简单的程序,但对于我的一生,我记不起名字了。
【解决方案2】:

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

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

您可以在文档中找到更多关于如何使用 curses 以使其完全按照您想要的方式进行操作的信息

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 2012-06-03
    • 1970-01-01
    • 2011-09-02
    • 2021-10-10
    • 1970-01-01
    • 2012-06-17
    • 2016-12-03
    • 2015-09-28
    相关资源
    最近更新 更多