如何在python中创建一个参数接受多个输入

1 python

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

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

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

有没有其他方法可以做到这一点,而无需在函数中添加第三,第四和第n个参数?

doo*_*des 6

当然你可以传递一个列表,但你也可以使用*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")
Run Code Online (Sandbox Code Playgroud)

或者作为列表或者iter

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"])
Run Code Online (Sandbox Code Playgroud)

这是*args和**kwargs的好SO