planetp planetp - 1 year ago 111
Python Question

How do I reliably split a string in Python?

In Perl I can do:

my ($x, $y) = split /:/, $str;

And it will work whether or not the string contains the pattern.

In Python, however this won't work:

a, b = "foo".split(":") # ValueError: not enough values to unpack

What's the canonical way to prevent errors in such cases?

Answer Source

If you're splitting into just two parts (like in your example) you can use str.partition() to get a guaranteed argument unpacking size of 3:

>>> a, sep, b = "foo".partition(":")
>>> a, sep, b
('foo', '', '')

str.partition() always returns a 3-tuple, whether the separator is found or not.

Another alternative is to use extended unpacking, as described in @cdarke's answer:

>>> a, *b = "foo".split(":")
>>> a, b
('foo', [])

This assigns the first split item to a and the list of remaining items (if any) to b.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download