开发者

How can I pass a user input string to a function as arguments in a python script?

I want to pass a user input string to a function, using the space separated word开发者_运维技巧s as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give.


def your_function(*args):
    # 'args' is now a list that contains all of the arguments
    ...do stuff...

input_args = user_string.split()
your_function(*input_args) # Convert a list into the arguments to a function

http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists

Granted, if you're the one designing the function, you could just design it to accept a list as a single argument, instead of requiring separate arguments.


The easy way, using str.split and argument unpacking:

f(*the_input.split(' '))

However, this won't perform any conversions (all arguments will still be strings) and split has a few caveats (e.g. '1,,2'.split(',') == ['1', '', '2']; refer to docs).


A couple of options. You can make the function take a list of arguments:

def fn(arg_list):
    #process

fn(["Here", "are", "some", "args"]) #note that this is being passed as a single list parameter

Or you can collect the arguments in an arbitrary argument list:

def fn(*arg_tuple):
    #process

fn("Here", "are", "some", "args") #this is being passed as four separate string parameters

In both cases, arg_list and arg_tuple will be nearly identical, the only difference being that one is a list and the other a tuple: ["Here, "are", "some", "args"] or ("Here", "are", "some", "args").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜