[英]How do I add multiple string arguments to my typing function in Python?
I made a type() function which functions similarly to print except it types character by character.我制作了一个 type() function ,它的功能类似于 print ,除了它是逐字符输入的。 The problem is, when I try to implement multiple str arguments it just prints everything at once.问题是,当我尝试实现多个 str arguments 时,它只会一次打印所有内容。
The code I used originally was:我最初使用的代码是:
import sys
import time
def type(text):
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05)
print()
In order to add more str arguments, I did:为了添加更多 str arguments,我做了:
import sys
import time
def type(*text):
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05)
print()
In practice, however, it usually just prints everything at once, like a normal print function. Any pointers?然而,在实践中,它通常只是一次打印所有内容,就像正常打印 function 一样。有任何指示吗?
If text
is a list, and the length of it varies, you can do:如果text
是一个列表,并且它的长度各不相同,你可以这样做:
def type(text):
for string in text:
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05)
print()
So you loop through the lists for each string, and for each string you loop through all the characters.因此,您遍历每个字符串的列表,并为每个字符串遍历所有字符。
In the case of using the *args
pattern在使用*args
模式的情况下
def func(*args):
...
func(a, b, c) # Then args is a tuple (a, b, c) inside the function.
args
will be a tuple inside the function. Your first function has text
which is a string, while in your second text
is a list of strings. args
将是 function 中的一个元组。您的第一个 function 的text
是一个字符串,而在您的第二个text
中是一个字符串列表。 So you'll need to either combine them all into one string like text = ''.join(text)
or iterate through each因此,您需要将它们全部组合成一个字符串,如text = ''.join(text)
或遍历每个字符串
for string in text:
for char in string:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.