简体   繁体   中英

how to define function with variable arguments in python - there is 'but'

I am going to define a function which takes a variable number of strings and examines each string and replaces / with - . and then return them back. (here is my logic problem - return what?)

def replace_all_slash(**many):
    for i in many:
        i = i.replace('/','-')
    return many

is it correct? how can i recollect the strings as separate strings again?

example call:

 allwords = replace_all_slash(word1,word2,word3)

but i need allwords to be separate strings as they were before calling the function. how to do this?

i hope i am clear to understand

You want to use *args (one star) not **args :

>>> def replace_all_slash(*words):
   return [word.replace("/", "-") for word in words]

>>> word1 = "foo/"
>>> word2 = "bar"
>>> word3 = "ba/zz"
>>> replace_all_slash(word1, word2, word3)
['foo-', 'bar', 'ba-zz']

Then, to re-assign them into the same variables, use the assignment unpacking syntax:

>>> word1
'foo/'
>>> word2
'bar'
>>> word3
'ba/zz'
>>> word1, word2, word3 = replace_all_slash(word1, word2, word3)
>>> word1
'foo-'
>>> word2
'bar'
>>> word3
'ba-zz'

Solution one: create a new list and append that that:

def replace_all_slash(*many):
    result = []
    for i in many:
        result.append(i.replace('/','-'))
    return result

Solution two using a list comprehension:

def replace_all_slash(*many):
    return [i.replace('/','-') for i in many]

You should rewrite your function:

def replace_all_slash(*args):
    return [s.replace('/','-') for s in args]

and you can call it this way:

w1,w2,w3 = replace_all_slash("AA/","BB/", "CC/")

分解调用代码中的参数需要每个字符串的变量。

word1,word2,word3 = replace_all_slash(word1,word2,word3) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM