2

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

Huzaifa Imran
  • 119
  • 2
  • 8

1 Answers1

3

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.
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Will this work even if function has multiple different arguments instead of *args? i.e func(arg1, arg2, arg3, arg4): #code I know it will throw an error if the user passes more arguments than parameters – Huzaifa Imran Aug 25 '20 at 13:38
  • 1
    Yes it will, the important part is `*user_input.split()` notice the `*` in front. – Cory Kramer Aug 25 '20 at 13:40