Reputation: 3112
I want to pass a user input string to a function, using the space separated words as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give.
Upvotes: 1
Views: 8484
Reputation: 4887
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")
.
Upvotes: 1
Reputation:
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).
Upvotes: 1
Reputation: 527378
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.
Upvotes: 3