Is there of a way to pass a list of strings as comma separated strings to a function's args in python

Viewed 1455

I want to take strings from the user without any limit and pass it into a function as different parameters for e.g

user_input = "Hello World! It is a beautiful day."

I want to pass this string split by spaces as parameters into a function i.e

func("Hello", "World!", "It", "is", "a", "beautiful", "day.")

And I cannot pass a list or tuple, it has to be multiple strings. I am new to python, sorry if the solution is very simple

1 Answers

You can use *args (and **kwargs if needed) for this. (More details here)

def func(*args):
    for s in args:
        print(s)

Then in your call you can use * to unpack the result of split into individual arguments. (More about extended iterable unpacking)

>>> user_input = "Hello World! It is a beautiful day."
>>> func(*user_input.split())
Hello
World!
It
is
a
beautiful
day.
Related