How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?
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?
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 for Python 3.x is to use extended iterable unpacking:
>>> a, *b = 'foo'.split(':') >>> a, b ('foo', )
This assigns the first split item to
a and the list of remaining items (if any) to
★ Back to homepage or read more recommendations: