planetp planetp - 7 months ago 24
Python Question

How to 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?


Use str.partition():

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

It will always return a 3-tuple, whether the separator is found or not.