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
str.split
Returns a list of substrings split at each occurrence of sep. If sep is None (default), runs of any whitespace are the separator and leading/trailing whitespace is discarded; if sep is given, empty fields between adjacent separators are preserved.
str.splitlines
Splits the string at universal line boundaries (\n, \r, \r\n, and other Unicode line terminators). Unlike split('\n'), it does not produce a trailing empty string when the input ends with a newline.
str.find
Returns the lowest index in the string where substring sub is found within the slice [start:end]. Returns -1 if the substring is not found, unlike index() which raises ValueError.
str.join
Returns a string built by concatenating every string in the iterable, separated by the string on which join is called. Every element of the iterable must be a str, or TypeError is raised.