如何为Python中的打字效果函数添加多个字符串参数?
问题解决:type()函数多参数下逐字符输出失效
我编写了一个type()函数,功能类似print,但会逐字符输出。原本的函数仅支持单个字符串参数,为了添加多字符串参数,我将参数改为*text,但实际运行时却像普通print函数一样一次性输出所有内容,求解决方法。
原代码:
import sys import time def type(text): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.05) print()
修改后的代码:
import sys import time def type(*text): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.05) print()
问题原因
使用*text时,所有传入的参数会被打包成一个元组。原来的循环for char in text现在遍历的是元组里的每一个完整字符串,而不是字符串中的单个字符,所以会直接输出整个字符串,失去了逐字符打印的效果。
解决方案
方案1:逐参数逐字符打印(无自动空格)
遍历元组中的每个字符串,再对每个字符串逐字符输出:
import sys import time def type(*text): for string in text: for char in string: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.05) print()
方案2:模拟print默认行为(自动加空格,支持非字符串参数)
先将所有参数转为字符串并用空格连接,再逐字符输出,和原生print的参数分隔逻辑一致:
import sys import time def type(*text): content = ' '.join(str(item) for item in text) for char in content: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.05) print()
内容的提问来源于stack exchange,提问作者Euler
相关产品推荐
相关产品推荐

