Reputation: 11
I basically have this input I want to split into different variables using a function, but the problem is that some I want to split into 2 variables, some 3, etc. For example:
day, month, year = input("Birthday: ").split(",")
in this code you would input something like "1, January, 2000" and it would sort the day, month, and year into different variables, namely "day", "month", and "year". However, I want there to be an option for the "split" to not happen when the string is empty. So, I decided to make a function doing this.
For the function part, I have something like the below.
def splitText(input, thing1, thing2, thing3):
if input != "":
thing1, thing2, thing3 = input.split(",")
bDay = input("Birthday: ")
splitText(bDay, day, month, year)
But this code has a problem, that there are only 3 "things" you can input into the arguments. I want it to be variable, where you can put 2, 3, 4, any number of arguments into the function. I've tried using "*args," but I'm just not so sure how to make that work for the rest of my code and whatnot.
Any help would be appreciated, either to fix this problem or just to complete the objective in a more efficient way :D
Upvotes: 1
Views: 832
Reputation: 1455
PEP 3132 -- Extended Iterable Unpacking
using this you can unpack string containing n number of words.
bDay = input("Birthday: ")
*a_lst, = bDay.split(',')
#Birthday: 15,july,2000
#['15', 'july', '2000']
Instead of using variables, I would just use dictionary where I can dynamically assign key and value to it.
def splitText(a_lst):
lst = ['day','month','year']
d = {}
for i in range(len(a_lst)):
for j in range(len(lst)):
if i == j :
d[lst[j]] = a_lst[i]
return d
print(splitText(a_lst))
#Birthday: 15,july,2000
#{'day': '15', 'month': 'july', 'year': '2000'}
#Birthday: 28
#{'day': '28'}
Upvotes: 0
Reputation: 454
You can use *args to take multiple parameters
def my_func(parameter1, parameter2, parameter3, *args): # *args takes infinite parameters
print("Parameter1:", parameter1) # Printing parameter 1-3
print("Parameter2:", parameter2)
print("Parameter3:", parameter3)
for argument in args: # For ever argument in our *args
print('Argument:', argument) # Print the argument
my_func('a', 'b', 'c', 'd', 'e', 'f')
Upvotes: 1