1

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.

1
  • Is this through in-program input or passing command line arguments to the program? Commented Nov 3, 2010 at 19:53

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

2 Comments

In the vast majority of cases where people write .split(' ') what they really should have written is .split().
the example you set, is not a caveat, it's just logical! (because it split at the commas)
1

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").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.