Call text.partition(sep)[2] to extract everything after the first occurrence of sep—which splits text into (before, sep, after) in a single C-level pass and safely returns "" if sep is missing without raising ValueError—or text.rpartition(sep)[2] when you want everything after the last occurrence of sep (falling back to the entire original string if sep is absent).
Basic Example
url = "[https://example.com/api/v1/users/profile](https://example.com/api/v1/users/profile)"
# 1. Recommended for FIRST occurrence (`str.partition` — never raises ValueError):
after_protocol = url.partition("://")[2]
print(after_protocol)
# Output: [example.com/api/v1/users/profile](https://example.com/api/v1/users/profile)
# 2. Recommended for LAST occurrence (`str.rpartition` — ideal for filenames/paths):
filename = url.rpartition("/")[2]
print(filename)
# Output: profile
# 3. Behavior when the delimiter substring is NOT found:
missing = "no_delimiter_here"
print(repr(missing.partition("::")[2])) # '' (empty string — safe default)
print(repr(missing.rpartition("::")[2])) # 'no_delimiter_here' (returns full string!)
Key Details & Edge Cases
- Why
text.partition(sep)[2]beatstext.split(sep, 1)[1]:- When
sepis missing fromtext,text.split(sep, 1)returns a 1-element list[text], so indexing[1]crashes withIndexError: list index out of range.text.partition(sep)always returns a 3-tuple(head, sep, tail)—sotext.partition(sep)[2]is guaranteed never to raiseIndexErrororValueError.
- When
- Crucial difference when
sepis missing betweenpartitionandrpartition:text.partition(sep)puts the unmatched string in index[0]and leaves index[2]as"".text.rpartition(sep)puts the unmatched string in index[2]and leaves index[0]as"".- If you want
""(orNone) when usingrpartitionandsepis absent, check the middle elementmatched_sep(_, matched_sep, tail = text.rpartition(sep); result = tail if matched_sep else "").
- Including the delimiter itself (
sep + after):- Because
partition()returns(before, matched_sep, after), keeping the delimiter is trivial via_, sep_found, after = text.partition(sep); result = sep_found + after.
- Because
- Case-insensitive or pattern-based delimiters (
re.split/re.search):- When the marker varies in case or formatting (e.g.,
"Error:","ERROR:","error -"), usere.split(r"error:\s*", text, maxsplit=1, flags=re.IGNORECASE)(taking[1]iflen(parts) > 1) orm = re.search(r"error:\s*(.*)", text, flags=re.IGNORECASE | re.DOTALL)(withre.DOTALLso.matches across newlines\n).
- When the marker varies in case or formatting (e.g.,
- Slicing with
str.find()when performance in tight loops matters:idx = text.find(sep)returns-1if missing; slicingtext[idx + len(sep):] if idx != -1 else ""avoids allocating thebeforeprefix string whenbeforeis megabytes long.
Comparison of Substring Extraction Methods in Python
| Method | Matches First or Last Occurrence? | Return Value When sep Is Missing |
Allocates Prefix Substring? | Best Used When |
|---|---|---|---|---|
text.partition(sep)[2] (Recommended for first match) |
First | "" (empty string; never raises) |
Yes (3-tuple) | Extracting everything after the first occurrence of a known delimiter (":", "=", "://"). |
text.rpartition(sep)[2] (Recommended for last match) |
Last | Full original text (check [1] if "" is needed) |
Yes (3-tuple) | Extracting the tail after the final occurrence (e.g., final / in a URL or final . in a filename). |
text.split(sep, 1)[1] |
First | Raises IndexError if sep is absent |
Yes (2-element list) | Only when sep is guaranteed to exist (prefer .partition(sep)[2] otherwise). |
text[idx + len(sep):] via text.find(sep) |
First (or Last with .rfind()) |
Explicit fallback ("" or None via idx != -1) |
No (slices only the tail) | Very large strings (MBs) where avoiding allocation of the prefix saves memory. |
re.search(r"pattern(.*)", text, re.DOTALL) |
First | None (no match object) |
Match group only | Case-insensitive delimiters, variable whitespace, or regex-based markers. |
You must log in or register to comment.