How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?

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 b.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)