str.partition()
Split the string at the FIRST occurrence of sep, returning a fixed-shape three-tuple: what came before, the separator itself, and what came after.
Demo
partition always returns exactly three strings — no guessing at tuple length. When the separator is not found, before is the entire string and the other two slots are empty; when it IS found, the separator itself is preserved in the middle slot. Splitting a value that contains additional separators only splits at the first — the rest stays in the tail.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sep | str | yes | Substring to split on. Empty string raises ValueError. First occurrence only. |
Return value
tuple[str, str, str] — Always a 3-tuple (before, sep, after). If sep is not found: (original_string, "", "").
Common patterns
key, _, value = line.partition("=")
before, sep, after = url.partition("://") rest = after if sep else before
first, _, rest = sentence.partition(" ")
Examples
Pitfalls
_, _, value = "no-eq-here".partition("=") # value is "" — the data went into slot 0
before, sep, after = s.partition("=") if sep: key, value = before, after
"hello".partition("")
if sep: a, s, b = text.partition(sep)
"a=b=c".partition("=")
"a=b=c".split("=")
When to use
- Key-value strings where the value may contain the separator
- "Split if present, keep original otherwise" in one call
- Head + tail extraction without materializing an N-way split
- Getting a fixed-shape return you can always unpack into three names
- Full N-way split → split
- Last-occurrence split → rpartition
- Regex-based splits → re.split
Notes
FAQ
partition splits at the FIRST occurrence only and always returns three items (before, sep, after). split can split every occurrence and does not preserve the separators. partition is safer for "take one, leave the rest" parsing.