Swastik
Swastik

Reputation: 11

How to split a string into multiple variables & if not enough values, assign the variable as a particular value?

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 like this:

ValueError: not enough values to unpack (expected 7, got 3)

Upvotes: 1

Views: 686

Answers (3)

Mohammad
Mohammad

Reputation: 51

Here is a suggestion (updated based on a comment from Blckknght)

def fit(mystring, expected_length, replacement_value):
    while len(mystring)<expected_length:
        mystring +=replacement_value
    return mystring

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

Upvotes: 1

Mark Tolonen
Mark Tolonen

Reputation: 177674

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.

Upvotes: 0

Barmar
Barmar

Reputation: 781004

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

Upvotes: 1

Related Questions