Skip to main content
 首页 » 编程设计

python之如何使python中的参数接受多个输入

2025年05月04日16jackei

我对 python 还是个新手;所以,对于这个有点模糊的问题感到抱歉。我只是好奇是否可以向一个参数添加多个输入。 例如:

def censored(sentence, word): 
    if word in sentence: 
        sentence = sentence.replace(word, "*" * len(word)) 
    return sentence 
print censored("foo off", "foo") 

这将打印出“**** off”。这就是我想要的;但是,如果我想添加除“foo”之外的其他输入怎么办?

有没有另一种方法可以做到这一点而不必在函数中添加第三个、第四个和第 n 个参数?

请您参考如下方法:

当然你可以传递一个列表,但你也可以只使用 *args。有时这取决于您希望如何使用该功能。

def censored(sentence, *args): 
  for word in args:     
    if word in sentence: 
        sentence = sentence.replace(word, "*" * len(word)) 
  return sentence 
print censored("foo off", "foo", "bar") 

或者作为列表或迭代器

def censored(sentence, words): 
  for word in words:     
    if word in sentence: 
        sentence = sentence.replace(word, "*" * len(word)) 
  return sentence 
print censored("foo off", ("foo", "bar")) 
print censored("foo off", ["foo", "bar"]) 

Here is a good SO for *args and **kwargs