在Python中如何修改已打印的文本?

16 投票
6 回答
37852 浏览
提问于 2025-04-16 14:22

我正在写一个Python程序,我希望它能在打印文本后进行修改。比如说,我想打印“hello”,然后每秒擦掉一个字母。我该怎么做呢?

另外,我听说过curses这个东西,但我没法让它工作,而且我不想只是不断创建新行,直到旧的文本消失在屏幕上。

6 个回答

1

你可以使用这个:

调用这些模块:

import time
import sys

然后复制这个方法:

    # Custom Print Method
    def custom_print(string, how = "normal", dur = 0, inline = True):

只复制这个部分,让方法进行类型检查

# string = the string to print & how = way to print & dur = time to print whole word or letter & inline = print on single line or not
if how == "typing": # if how is equal to typing then run this block of code
    letter = 1
    while letter <= len(string):
        new_string = string[0:letter]
        if inline: sys.stdout.write("\r")
        sys.stdout.write("{0}".format(new_string))
        if inline == False: sys.stdout.write("\n")
        if inline: sys.stdout.flush()
        letter += 1 
        time.sleep(float(dur))

或者只复制这个部分,让字符串反向打印

if how == "reverse": # if how is equal to reverse then run this block of code
    new_string = string
    while len(new_string) > 0:
        if inline == True: sys.stdout.write("\r")
        sys.stdout.write('{message: <{fill}}'.format(message=new_string, fill=str(len(string))))
        if inline == False: sys.stdout.write("\n")
        if inline == True: sys.stdout.flush()
        new_string = new_string[0:len(new_string) - 1]
        time.sleep(float(dur))

或者只复制这个部分,让普通字符串正常打印

if how == "normal": # if how is equal to normal then run this block of code
    sys.stdout.write("\r")
    sys.stdout.write(string)
    time.sleep(float(dur))
    sys.stdout.write("\n")

或者你可以把所有内容放在方法里,这样就有了所有选项

你只需要调用 custom_print(),而不是 print

# custom_print("string", "howtoprint", seconds in int, inline:true or false)
custom_print("hello", "reverse", 1) # for reverse printing hello
custom_print("hello", "typing", 1) # for typing hello slowly
custom_print("hello", "normal", 0) # for just printing hello
custom_print("hello") # for just printing hello
4

如果你想要输出多行内容,你也可以每次先清空屏幕,然后再重新打印所有内容:

from time import sleep
import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

message = 'hello'
for i in range(len(message), 0, -1):
    cls()
    print message[:i]
    sleep(1)
16

这里有一种方法可以做到。

print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()

你也可以尝试使用ANSI转义序列,可能会有一些聪明的做法,比如:

sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
    time.sleep(1)
    sys.stdout.write('\033[D \033[D')
    sys.stdout.flush()

撰写回答