【问题标题】:How do I make a delay in the printing of each letter in my code?如何延迟打印代码中的每个字母?
【发布时间】:2022-10-01 01:50:13
【问题描述】:

我想在每个字符(例如 w、e、l、c、o、m、e)之间放置一个延迟,并尽可能少地导入。

import sys

starter_line = (\'Welcome to... \')
starter = []
for x in range(len(starter_line)):
        y = starter_line[x-1:x]
        starter.append(y)
print(\"\".join(starter))
        

我尝试使用睡眠和时间模块,但它只是给了我一个错误。

  • 使用sleep(和循环!)可能是在字符之间引入延迟的最佳方法。向我们展示您尝试了什么(以及您收到的错误)。
  • 请使用您在时间模块中遇到的错误编辑您的帖子

标签: python import delay


【解决方案1】:
import time`
text = 'Welcome to... '
x = ''
for characters in text:
    x += characters
    print(x)
    time.sleep(0.3) # 300 milliseconds

好吧,我不知道你在哪里尝试这样做。

但是,如果您尝试在 python 屏幕上进行此操作(运行或调试)

输出:

W
We
Wel
Welc
Welco
Welcom
Welcome
Welcome 
Welcome t
Welcome to
Welcome to.
Welcome to..
Welcome to...
Welcome to... 

但是,如果您尝试在“终端”上进行此操作

import time
import os

text = 'Welcome to... '
x = ''
for characters in text:
    x += characters
    print(x)
    time.sleep(0.3) # 300 milliseconds
    os.system('cls||clear') #this thing will clear your terminal screen

输出:

Welcome to...

【讨论】:

    【解决方案2】:

    您所要求的内容确实不清楚,但这是我相信您所要求的工作版本。此代码将字符串拆分为一个列表,每个字符都分开,然后遍历列表打印当前字母,然后等待 1 秒再执行此操作。 time.sleep () 不起作用的原因是因为您没有导入时间库。

    import time
    
    starter_line = ('Welcome to... ')
    
    for i in range(len(list(starter_line))):
        print(list(starter_line)[i])
        time.sleep(0.5)
    

    如果您可以更清楚地描述您想要的内容,那就太好了,因为我不知道您是否要在所有字符之间添加“,”,或者您是否想要像我发送的代码一样的时间延迟。

    【讨论】:

    • 对于这个不清楚的问题,我深表歉意,但我的意思是我希望在同一行中延迟打印每封信。
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多