![](/img/trans.png)
[英]How do I ignore a string in a function that accepts multiple arguments in python?
[英]How do I add multiple string arguments to my typing function in Python?
我制作了一個 type() function ,它的功能類似於 print ,除了它是逐字符輸入的。 問題是,當我嘗試實現多個 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()
為了添加更多 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()
然而,在實踐中,它通常只是一次打印所有內容,就像正常打印 function 一樣。有任何指示嗎?
如果text
是一個列表,並且它的長度各不相同,你可以這樣做:
def type(text):
for string in text:
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05)
print()
因此,您遍歷每個字符串的列表,並為每個字符串遍歷所有字符。
在使用*args
模式的情況下
def func(*args):
...
func(a, b, c) # Then args is a tuple (a, b, c) inside the function.
args
將是 function 中的一個元組。您的第一個 function 的text
是一個字符串,而在您的第二個text
中是一個字符串列表。 因此,您需要將它們全部組合成一個字符串,如text = ''.join(text)
或遍歷每個字符串
for string in text:
for char in string:
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.