簡體   English   中英

如何使用回車和換行符格式化文本?

[英]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 和 coloroma 答案都可以,但是在 try except 時,curses 會導致終端死機,並且它有點無法配置。 Coloroma 是最簡單的,也是我需要的答案。

至於使用\\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模塊在這里很有用。

快速演示:

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()創建一個覆蓋整個終端的“窗口”。不過也沒有必要

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

您可以在文檔中找到更多有關如何處理curses以使其完全按照您的要求執行的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM