You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:50:23