partition Splits Once And Never Raises
str.partition cuts at the first separator, rpartition at the last, and a missing separator returns the whole string with two empty halves instead of raising.
Code
header = 'Retry-After: 30, ETag: "a=b"'
# partition makes only the first cut: the header and the whole value separate safely, and colons or equals inside the value survive
name, sep, value = header.partition(":")
print(name, "|", sep, "|", value)
# rpartition cuts from the right: it takes everything after the last separator
filename, dot, ext = "archive.backup.tar.gz".rpartition(".")
print(filename, "|", ext)
# missing separator: it returns (the original string, '', ''), so callers skip the membership check
user, sep, domain = "local-only".partition("@")
print(repr(user), repr(sep), repr(domain))
# contrast: split cuts at every separator, and index throws ValueError outright on a miss
print(header.split(":"))
try:
"local-only".index("@")
except ValueError as exc:
print("index raises:", exc)What the code does
Top-level bindings header hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (index raises:), so every printed line maps back to its originating operation.
Statements that matter
except ValueError as exc:
print("index raises:", exc)
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `header`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.