Search code examples
pythonpython-3.xiterable-unpacking

Safely unpacking results of str.split


I've often been frustrated by the lack of flexibility in Python's iterable unpacking. Take the following example:

a, b = "This is a string".split(" ", 1)

Works fine. a contains "This" and b contains "is a string", just as expected. Now let's try this:

a, b = "Thisisastring".split(" ", 1)

Now, we get a ValueError:

ValueError: not enough values to unpack (expected 2, got 1)

Not ideal, when the desired result was "Thisisastring" in a, and None or, better yet, "" in b.

There are a number of hacks to get around this. The most elegant I've seen is this:

a, *b = mystr.split(" ", 1)
b = b[0] if b else ""

Not pretty, and very confusing to Python newcomers.

So what's the most Pythonic way to do this? Store the return value in a variable and use an if block? The *varname hack? Something else?


Solution

  • This looks perfect for str.partition:

    >>> a, _, b = "This is a string".partition(" ")
    >>> a
    'This'
    >>> b
    'is a string'
    >>> a, _, b = "Thisisastring".partition(" ")
    >>> a
    'Thisisastring'
    >>> b
    ''
    >>>