替换终端中的多行字符串

Exo*_*arf 1 python-3.x

我正在尝试编写一些代码,这些代码将覆盖其以前的输出,例如原始输出是"1",但"1"被替换为"2". 这使得看起来好像"1"从一开始就没有被输出过。我有一个名为 的列表列表board,我使用以下代码将此列表转换为多行字符串:

rendered_board = ""
for y in range(board_height):
    for x in range(board_width):
        rendered_board += board[y][x]

    rendered_board += "\n"
Run Code Online (Sandbox Code Playgroud)

我得到了我想要的字符串,但是,我希望能够用新字符串更新该字符串并用它替换旧字符串。

输出示例:

+-------+                      +-------+
|       |  *gets replaced by*  |       |
|       | -------------------> |   *   |
|       |                      |       |
+-------+                      +-------+
Run Code Online (Sandbox Code Playgroud)

end="\r" 目前我一直在尝试使用例如来做到这一点

print(rendered_board, end="\r")
update_board()
print(rendered_board, end="\r")
Run Code Online (Sandbox Code Playgroud)

这导致了以下输出:

+-------+
|       |
|       |
|       |
+-------+
+-------+
|       |
|   *   |
|       |
+-------+
Run Code Online (Sandbox Code Playgroud)

zwe*_*wer 5

这并不像您想象的那么微不足道。您可以使用\r(回车)返回当前行,或\b向后移动一个字符 - 两者都让人想起早期的电子打字机时代 - 但要在屏幕上移动,您需要对终端进行更多控制。当然,您可以在 Windows 上调用os.system('clear')*nix /os.system('cls')来清除整个屏幕并再次绘制它,但这并不优雅。

相反,Python 提供了curses专门为此目的而设计的模块。下面是如何使用它的简单演示:

import curses
import time

console = curses.initscr()  # initialize is our playground

# this can be more streamlined but it's enough for demonstration purposes...
def draw_board(width, height, charset="+-| "):
    h_line = charset[0] + charset[1] * (width - 2) + charset[0]
    v_line = charset[2] + charset[3] * (width - 2) + charset[2]
    console.clear()
    console.addstr(0, 0, h_line)
    for line in range(1, height):
        console.addstr(line, 0, v_line)
    console.addstr(height-1, 0, h_line)
    console.refresh()

def draw_star(x, y, char="*"):
    console.addstr(x, y, char)
    console.refresh()

draw_board(10, 10)  # draw a board
time.sleep(1)  # wait a second
draw_star(6, 6)  # draw our star
time.sleep(1)  # wait a second
draw_star(6, 6, " ")  # clear the star
draw_star(3, 3)  # place the star on another position
time.sleep(3)  # wait a few seconds

curses.endwin()  # return control back to the console
Run Code Online (Sandbox Code Playgroud)

当然,您可以比这更奇特,但它应该让您了解如何使用它。