Split or Extract Strings into Arguments of Function?
Question:
I have a function that accepts multiple arguments. I can call it like:
i_take_strings('one', 'two', 'and_the_letter_C')
But suppose I want to determine the arguments dynamically, for example, by splitting a string. I tried:
s = 'one two and_the_letter_c'
i_take_strings(x for x in s.split())
but I get an error message. What is wrong, and how do I fix it?
Answers:
s.split()
already returns a list so you can pass it to your function as variable arguments
by prepending *
like follows:
i_take_strings(*s.split())
I have a function that accepts multiple arguments. I can call it like:
i_take_strings('one', 'two', 'and_the_letter_C')
But suppose I want to determine the arguments dynamically, for example, by splitting a string. I tried:
s = 'one two and_the_letter_c'
i_take_strings(x for x in s.split())
but I get an error message. What is wrong, and how do I fix it?
s.split()
already returns a list so you can pass it to your function as variable arguments
by prepending *
like follows:
i_take_strings(*s.split())