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

时间:2015-08-20 19:20:20

标签: python

我还是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个参数?

5 个答案:

答案 0 :(得分: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")

或作为列表或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"])

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

答案 1 :(得分:3)

如果存在任何单词,您可以迭代不良单词并使用replace执行替换。

def censored(sentence, bad_words):
    for word in bad_words:
        sentence = sentence.replace(word, '*' * len(word))
    return sentence

>>> censored('foo off ya dingus', ['foo', 'dingus'])
'*** off ya ******'

答案 2 :(得分:1)

除了CoryKramer:

或者创建一个全局变量并使用单词的默认值。

EXLCUDED_WORDS = ['foo', 'dingus']

def censored(sentence, bad_words=EXCLUDED_WORDS):
    # check if the list is not empty
    if bad_words:
        for word in bad_words:
            sentence = sentence.replace(word, '*' * len(word))
    return sentence

censored('foo off ya dingus')

答案 3 :(得分:0)

你可以把它作为一个清单。

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","asp"])

答案 4 :(得分:0)

有几种方法可以做到这一点。最简单的方法是将一组字符串作为第二个参数传递。例如:

def censored(sentence, words):
    for word in words:
        if word in sentence:
            sentence = sentence.replace(word, "*" * len(word))
    return sentence

所以,你的用法可能是:

print("foo that ship", ["foo", "ship"]) # passing a list
print("foo that ship", {"foo", "ship"}) # passing a set

另一种方式,但我不建议使用的方法是使用可变长度的参数列表,如:

def censored(sentence, *words):
    for word in words:
        if word in sentence:
            sentence = sentence.replace(word, "*" * len(word))
    return sentence

用法为:

print("foo that ship", "foo", "ship") # as many arguments as you'd like with the same function definition

这种方法的问题在于您无法轻松扩展禁止词的列表。但是,了解/理解它是一种有用的技术。