Python 打印缓慢(模拟打字)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4099422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:15:32  来源:igfitidea点击:

printing slowly (Simulate typing)

python

提问by TechplexEngineer

I am trying to make a textual game in python. All goes well however, I would like to make a function that will allow me to print something to the terminal, but in a fashion hat looks like typing.

我正在尝试用 python 制作一个文本游戏。然而,一切顺利,我想制作一个功能,让我可以在终端上打印一些东西,但时尚帽子看起来像打字。

Currently I have:

目前我有:

def print_slow(str):
    for letter in str:
        print letter,
        time.sleep(.1)

print_slow("junk")

The output is:

输出是:

j u n k

Is there a way to get rid of the spaces between the letters?

有没有办法摆脱字母之间的空格?

采纳答案by Mark Byers

In Python 2.x you can use sys.stdout.writeinstead of print:

在 Python 2.x 中,您可以使用sys.stdout.write代替print

for letter in str:
    sys.stdout.write(letter)
    time.sleep(.1)

In Python 3.x you can set the optional argument endto the empty string:

在 Python 3.x 中,您可以将可选参数end设置为空字符串:

print(letter, end='')

回答by Sebastian

Try this:

尝试这个:

def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.1)

print_slow("Type whatever you want here")

回答by Bill Gross

This is my "type like a real person" function:

这是我的“像真人一样的类型”功能:

import sys,time,random

typing_speed = 50 #wpm
def slow_type(t):
    for l in t:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(random.random()*10.0/typing_speed)
    print ''

回答by Ahmed

Try this:

尝试这个:

import sys,time

def sprint(str):
   for c in str + '\n':
     sys.stdout.write(c)
     sys.stdout.flush()
     time.sleep(3./90)

sprint('hello world')