python: 用另一行替换打印行的文本

python: replace a printed line's text with another line

我想打印一行并将该行替换为另一文本。 示例代码:

import os
import time
lst = ["|","/","-","\"]
num = 0
for i in range(500):
    os.system("cls") #i don't want to clear the whole terminal window.
    print(lst[num])
    if num == 3:
        num = 0
    else:
        num = num + 1
    time.sleep(0.2)

就像我们使用 pip 安装 tar.gz 文件一样 在构建包的 setup.py 时,它会打印“building setup.py ,|,-,\” 而不会清除控制台..

我看过很多关于这个的帖子..但是他们都没有一个好的答案..

SPECS:
OS: Windows 7 SP1
Python: Python 3.8.10
Arch: x86 (32-bit)

可以使用\r(回车return)。此外,您不需要 num 作为索引 lst 的额外变量,您可以使用现有的 i 来索引 lst

import time
lst = ["|","/","-","\"]
num = 0
for i in range(500):
    print(lst[i % 4], end="\r")     # i will be between 0 and 3 both inclusive
    time.sleep(0.2)