Search code examples
pythonpython-3.xiterable-unpacking

Is it possible to assign a default value when unpacking?


I have the following:

>>> myString = "has spaces"
>>> first, second = myString.split()
>>> myString = "doesNotHaveSpaces"
>>> first, second = myString.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I would like to have second default to None if the string does not have any white space. I currently have the following, but am wondering if it can be done in one line:

splitted = myString.split(maxsplit=1)
first = splitted[0]
second = splitted[1:] or None

Solution

  • May I suggest you to consider using a different method, i.e. partition instead of split:

    >>> myString = "has spaces"
    >>> left, separator, right = myString.partition(' ')
    >>> left
    'has'
    >>> myString = "doesNotHaveSpaces"
    >>> left, separator, right = myString.partition(' ')
    >>> left
    'doesNotHaveSpaces'
    

    If you are on python3, you have this option available:

    >>> myString = "doesNotHaveSpaces"
    >>> first, *rest = myString.split()
    >>> first
    'doesNotHaveSpaces'
    >>> rest
    []