Home > Back-end >  How to split a string into multiple variables & if not enough values, assign the variable as a parti
How to split a string into multiple variables & if not enough values, assign the variable as a parti

Time:11-03

I have this code (Python 3.9):

vdam = {"mirror": 0, "door": 1, "windShield": 2}
vdam2 = list(vdam.items())
vdam3 = [a[0] for a in vdam2]
vdam4 = ' '.join([str(ele) for ele in vdam3])
a, b, c, d, e, f, g = vdam4.split()

I want to split the string into multiple variables but at the same time, if not enough values to be split, all other left variables get assigned as a particular value. The above code generates the error: ValueError: not enough values to unpack (expected 7, got 3)

CodePudding user response:

Append default values to the list to make it contain the number of elements equal to the number of variables. Then assign them.

vdam5 = vdam4.split()
if len(vdam5) < 7:
    vdam5  = [None] * (7 - len(vdam5))
a, b, c, d, e, f, g = vdam5

CodePudding user response:

vdam2-vdam4 are not needed, nor the .split(). List the keys and append enough defaults to handle 0-7 arguments. The final *_ captures the excess items:

>>> vdam = {"mirror": 0, "door": 1, "windShield": 2}
>>> a,b,c,d,e,f,g,*_ = list(vdam.keys())   [None]*7
>>> a,b,c,d,e,f,g
('mirror', 'door', 'windShield', None, None, None, None)

If you have varying defaults, this works by expanding the keys as parameters to the function:

>>> vdam = {"mirror": 0, "door": 1, "windShield": 2}
>>> a,b,c,d,e,f,g,*_ = list(vdam.keys())   [None]*7
>>> a,b,c,d,e,f,g
('mirror', 'door', 'windShield', None, None, None, None)

>>> def func(a=1,b=2,c=3,d=4,e=5,f=6,g=7):
...    return a,b,c,d,e,f,g
...
>>> a,b,c,d,e,f,g = func(*vdam.keys())
>>> print(a,b,c,d,e,f,g)
mirror door windShield 4 5 6 7

Note you could also use func(*vdam4.split()) as well if you have a space-delimited string.

CodePudding user response:

Here is a suggestion

def fit(x,y,z): #x:string, y:expected length, z:replacement value
    while len(x)<y:
        x  =z
    return x

vdam = {"mirror": 0, "door": 1, "windShield": 2}
vdam2 = list(vdam.items())
vdam3 = [a[0] for a in vdam2]
vdam4 = ' '.join([str(ele) for ele in vdam3])
a, b, c, d, e, f, g = fit(vdam4.split(),7,'A')
mirror door windShield A A A A
  • Related