planetp planetp - 1 year ago 101
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?

Answer Source

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.

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