splitting

str.partition

Splits the string at the first occurrence of sep and returns a 3-tuple (before, sep, after). If sep is not found, returns (original, '', '') — so unpacking is always safe.

str.partition(sep)

Parameters

Parameter Purpose
sep non-empty separator string
returns tuple[str, str, str] — (before, sep, after) or (original, '', '') on miss

Examples

>>> 'key=value'.partition('=')
('key', '=', 'value')

classic key/value split

>>> 'a=b=c'.partition('=')
('a', '=', 'b=c')

splits only on the FIRST match

>>> 'nothere'.partition('=')
('nothere', '', '')

sep missing -> original in slot 0, empties in 1 and 2

>>> 'abc'.partition('')
Traceback (most recent call last):
  ...
ValueError: empty separator

empty sep raises ValueError

Gotcha

Always returns a 3-tuple, so unpacking is safe. Empty sep raises ValueError. On miss, the original string is in slot 0 (not slot 2).

Related methods

← All Python string methods · Python built-ins