如何在字符间隔中打印字符串?

3 投票
7 回答
38678 浏览
提问于 2025-04-16 09:34

我想让一段文字显示得像是正在被逐字输入一样。所以我需要在每个字母后面加一点延迟。

我试着这样做:

import time

text = "Hello, this is a test text to see if all works fine."
for char in text:
   print char,time.sleep(0.2),

这样做效果不错,除了一个问题。我每输入一个字符后都会出现一个“None”。

这是输出的结果:

H None e None l None l None o None , None   None t None h None i None s None   None i None s None   None a None   None t None e None s None t None   None t None e None x None t None   None t None o None   None s None e None e None   None i None f None   None a None l None l None   None w None o None r None k None s None   None f None i None n None e None . None

我不知道为什么会这样。希望有人能帮我解决这个问题。

7 个回答

1

我觉得你的例子会把它们都打印在不同的行上(至少在Windows系统上是这样)。你可以使用打印到 sys.stdout 的方法来解决这个问题。

import time, sys
for character in text:
    sys.stdout.write(character)
    time.sleep(0.2)
3

你在打印 time.sleep(0.2) 的结果,而这个结果是 None。把它移到下一行去。

text = "Hello, this is a test text to see if all works fine."
for char in text:
    print char,
    time.sleep(0.2)

当然,你还有一个问题,就是每个字符之间有空格。这个问题可以通过把 print 换成 sys.stdout.write 来解决。

text = "Hello, this is a test text to see if all works fine."
for char in text:
    sys.stdout.write(char)
    time.sleep(0.2)
20

当然可以!请看下面的内容:

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用这些数据。这就像你从冰箱里拿出食材,然后在厨房里做饭一样。

有些时候,数据的格式可能会让我们感到困惑。就像你在做饭时,可能会遇到一些食材的包装上写着不同的单位,比如克、千克、盎司等等。为了让做饭更顺利,我们需要把这些单位统一成一种,方便使用。

在编程里,我们也会遇到类似的情况。我们需要把不同格式的数据转换成统一的格式,这样才能顺利地进行后续的操作。这个过程就叫做“数据转换”。

希望这个解释能帮助你更好地理解数据处理的基本概念!

>>> import time
>>> import sys
>>> blah = "This is written slowly\n"
>>> for l in blah:
...   sys.stdout.write(l)
...   sys.stdout.flush()
...   time.sleep(0.2)
...
This is written slowly

撰写回答