英文:
How to print one character at a time but maintain print function -- Python
问题
我正在开发一个基于Python的文本游戏,我希望在游戏中出现文字逐个字母显示的效果。这必须是一个函数,因为我希望这个效果适用于几乎所有的打印字符串。我正在使用下面的代码,这段代码我从这里获取的,它对于这个简单的例子效果很好,但问题是它不能识别撇号或连字符等字符,并且它不能保留我已经设置的换行,因此对于较长的文本无法正常工作。
有没有办法解决这个问题?如果至少能让它识别更多字符,并且每次使用新的slow()函数时都能在新行上打印,那将是很好的。
import sys, time
def slow(text, delay=0.02):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print
slow("Hello!")
谢谢,对于初学者的问题请见谅。
英文:
I am developing a text-based game on Python and I wanted to have the effect where letters appear one at a time. It has to be a function because I wanted the effect to apply to almost all printed strings. I am using the code seen below, which I got from here, and it works fine for this simple example, but the problem is that it does not recognize characters like apostrophes or hyphens and it does not retain the line breaks I have already set up, so it does not work for longer amounts of text.
Is there a way to get around this? If I could have it at least recognize more characters and have it print on a new line every time I use a new slow() function, that would be great.
import sys, time
def slow(text, delay=0.02):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print
slow("Hello!")
Thank you and apologize for the beginner question.
答案1
得分: 0
这一切都可以通过*print()*完成。
在输出每个字符后,必须输出一个新行。但是,输入字符串可能已经以'\n'结尾,所以不要重复它。
from sys import stdout
from time import sleep
def slow(text, delay=0.1):
if text: # 只有在字符串非空时处理
for c in text:
print(c, end='', flush=True)
sleep(delay)
if text[-1] != '\n':
print()
slow("Hello world!")
英文:
This can all be done with print()
It is a requirement that a newline is output after the individual characters. However, the input string may already end with '\n' so don't repeat it.
from sys import stdout
from time import sleep
def slow(text, delay=0.1):
if text: # only process if the string is not zero length
for c in text:
print(c, end='', flush=True)
sleep(delay)
if text[-1] != '\n':
print()
slow("Hello world!")
答案2
得分: -1
试试这个
import sys, time
def slow(text, delay=0.5):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print('\n')
slow("Hello!\nAlejandra R-")
slow("Hello!\nAlejandra R 2")
英文:
Try this
import sys, time
def slow(text, delay=0.5):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print('\n')
slow("Hello!\nAlejandra R-")
slow("Hello!\nAlejandra R 2")
答案3
得分: -2
import time
def print_one_at_a_time(text, sleep=0.1):
"逐个打印字符,每个字符之间暂停指定秒数"
text += '\n'
for c in text:
print(c, end='', flush=True)
time.sleep(sleep)
英文:
import time
def print_one_at_a_time(text, sleep=0.1):
"print a letter at a time, sleep certain seconds in between"
text += '\n'
for c in text:
print(c, end='', flush=True)
time.sleep(sleep)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论