如何让 Python 在同一行一次打印一个字符? [英] How to make Python print one character at a time on the same line?
问题描述
所以,我一直在尝试制作一个小程序,它会向用户提出各种问题并根据输入给出分支输出,并且我一直在尝试使打印文本一次出现在屏幕上的字符上,每个字符之间有很短的延迟,但在同一行上.我见过其他各种方法,例如
So, I've been trying to make a small program that asks a user various questions and gives branching outputs based on the input, and I've been trying to make the print text appear on screen on character at a time, with a short delay in between each character, but on the same line. I've seen other various methods such as
print "H",
print "e",
等,但这非常耗时,需要我为每个字母打印一个打印件.我已经看到了关于这个主题的其他问题,并尝试了放置在其中的代码,但到目前为止似乎都没有工作.有没有更简单的方法来打印我想要的东西,或者把它变成一个打印样式的功能?
etc, but that is very time consuming, requiring me to type out a print for each letter. I've seen other question on this topic, and tried the code placed in them, but none seem to work so far. Would there be an easier way to print what I want, or to make this into a print style function?
把它变成一个函数可能真的很容易,但我对 Python 有点初学者
Making this a function is probably REALLY easy, but I'm a bit of a beginner with Python
推荐答案
一个简单的 for
循环将从任何字符串中获取单个字符.唯一真正的技巧是在每个字符后刷新输出以使其立即打印.
A simple for
loop will get you the individual characters from any string. The only real trick is to flush the output after each character to make it print immediately.
import sys, time
for c in "Hello there!":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
print
让它成为一个函数确实很简单:
To make it a function is indeed simple:
def print1by1(text, delay=0.1):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print
print1by1("Hello there!")
这篇关于如何让 Python 在同一行一次打印一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!