Sub topic 6
Dividing at the First or Last Separator with partition
This chapter covers str.partition and str.rpartition, two methods that cut a string into exactly three parts at one separator. It assumes you can run Python scripts or use the REPL, and that you are comfortable with strings, tuples, tuple unpacking and basic for loops. It also assumes you know the split and rsplit behavior from the previous chapters, especially maxsplit.
What partition does
partition(sep) searches the string for the first occurrence of sep. It returns a tuple of three strings:
- everything before the separator,
- the separator itself,
- everything after the separator.
print("[email protected]".partition("@")) # ('user', '@', 'example.com')
print("a=b=c".partition("=")) # ('a', '=', 'b=c')Only the first match counts. In the second line, the second = stays inside the last part untouched.
rpartition(sep) does the same thing starting from the right end. It splits at the last occurrence:
print("a.b.c".rpartition(".")) # ('a.b', '.', 'c')
print("a=b=c".rpartition("=")) # ('a=b', '=', 'c')Strings are immutable, so neither method changes the original. Both return a new tuple, and the original string is unchanged. You must use the return value.
s = "key=value"
s.partition("=") # result thrown away
print(s) # key=value
head, sep, tail = s.partition("=")
print(head, tail) # key valueThe result always has three items
The key property of partition is that the tuple always has length 3, whether or not the separator is found. That differs from split, whose list length depends on the data.
When the separator is missing, partition returns the whole string first, then two empty strings. rpartition returns the two empty strings first, then the whole string:
print("no-at-sign".partition("@")) # ('no-at-sign', '', '')
print("no-at-sign".rpartition("@")) # ('', '', 'no-at-sign')The position of the whole string is the detail people forget. With partition, the leftover text lands in the first slot. With rpartition, it lands in the last slot. This matches the direction of the search: each method treats "not found" as if the separator lay beyond the end it started from.
Why this matters for unpacking
Compare unpacking the result of split(sep, 1) with unpacking partition:
line = "timeout" # no "=" in this line
try:
key, value = line.split("=", 1)
except ValueError as err:
print(err) # not enough values to unpack (expected 2, got 1)
key, sep, value = line.partition("=")
print(repr(key), repr(sep), repr(value)) # 'timeout' '' ''split returns a one-item list, so the two-name unpacking fails. partition always unpacks cleanly into three names. You then decide what a missing separator means by checking sep.
| Situation | `"k=v".split("=", 1)` | `"k=v".partition("=")` |
|---|---|---|
| Separator present | `['k', 'v']` | `('k', '=', 'v')` |
| Separator missing (`"kv"`) | `['kv']` | `('kv', '', '')` |
| Number of items | 1 or 2 | always 3 |
| Tells you whether it matched | only by checking the length | by checking the middle item |
Detecting whether the separator was found
The middle item is the separator when found and an empty string when not found. Because the separator cannot be empty (see below), an empty middle item reliably means "not found". An empty string is falsy, so this works:
head, sep, tail = "name: Ada".partition(":")
if sep:
print("found", repr(head), repr(tail)) # found 'name' ' Ada'
else:
print("no colon")Do not test if tail: for this purpose. The separator can be present with nothing after it, and then tail is empty even though the match succeeded:
print("key=".partition("=")) # ('key', '=', '')
print("=value".partition("=")) # ('', '=', 'value')Both of these are found, with one side empty. Only the middle item distinguishes them from the not-found case ('key', '', '').
Edge cases and errors
- Empty input.
"".partition(",")returns('', '', ''). - Empty separator.
"abc".partition("")raisesValueError: empty separator. There is no sensible place to cut, so Python refuses.split("")raises the same error. - Multi-character separators. The separator is matched as a whole substring:
"a--b--c".partition("--")returns('a', '--', 'b--c'). - Case. Matching is case-sensitive.
"Key=Value".partition("key")does not match. - Wrong type.
"abc".partition(None)raisesTypeError. Unlikesplit(),partitionhas no "no argument" orNoneform, so it cannot split on whitespace runs. Usesplit(None, 1)for that. - Bytes.
byteshas the same methods, but the separator must also be bytes:b"a=b".partition(b"=")returns(b'a', b'=', b'b').
print("".partition(",")) # ('', '', '')
print("a--b--c".partition("--")) # ('a', '--', 'b--c')
print("a b c".split(None, 1)) # ['a', 'b c']
try:
"abc".partition("")
except ValueError as err:
print(err) # empty separatorCommon patterns
Taking one side only
When you need just one part, unpack the others into _. By convention, _ marks a value you do not use.
email = "[email protected]"
user, _, domain = email.partition("@")
print(user) # user
print(domain) # example.com
command = "git commit -m 'fix'"
name, _, rest = command.partition(" ")
print(name) # git
print(rest) # commit -m 'fix'Stripping a comment
partition is a compact way to remove everything after a marker. If the marker is absent, the first item is the whole string, so no special case is needed:
for line in ["port = 8080 # default", "host = localhost"]:
code, _, _ = line.partition("#")
print(repr(code.strip())) # 'port = 8080', then 'host = localhost'Getting a file extension with rpartition
File names can contain many dots, so you want the last one. rpartition is the natural tool:
name = "report.final.tar.gz"
stem, dot, ext = name.rpartition(".")
print(stem) # report.final.tar
print(ext) # gzCheck dot before trusting ext. A name with no dot puts the whole string in the last slot, which would make the file name look like an extension:
stem, dot, ext = "Makefile".rpartition(".")
print(repr(stem), repr(dot), repr(ext)) # '' '' 'Makefile'
ext = ext if dot else ""
print(repr(ext)) # ''Hidden files such as .bashrc also produce ('', '.', 'bashrc'), which looks like an extension named bashrc. If you handle real file paths, os.path.splitext or pathlib.Path.suffix already deal with these cases. Use rpartition for file-like strings that are not paths.
Peeling a URL in stages
Chaining partition calls lets you cut a string in several steps, each time keeping only the remainder:
url = "https://example.com/a/b?x=1"
scheme, _, rest = url.partition("://")
host, _, path = rest.partition("/")
path, _, query = path.partition("?")
print(scheme) # https
print(host) # example.com
print(path) # a/b
print(query) # x=1This works for well-formed input only. For real URLs, use urllib.parse.urlsplit, which handles ports, fragments, credentials and the missing-part cases.
A small parser that uses both ideas
The function below parses key = value lines with optional # comments. It uses partition for the comment, then for the key/value split, and it uses the middle item to report malformed lines.
def parse_line(line):
"""Return (key, value), or None for blank and comment-only lines."""
content, _, _ = line.partition("#")
content = content.strip()
if not content:
return None
key, sep, value = content.partition("=")
if not sep:
raise ValueError(f"missing '=' in line: {line!r}")
return key.strip(), value.strip()
for text in ["name = Ada # author", "# only a comment", "path = /a=b", "oops"]:
try:
print(parse_line(text))
except ValueError as err:
print("error:", err)The output is:
('name', 'Ada')
None
('path', '/a=b')
error: missing '=' in line: 'oops'The third line shows why splitting at the first = matters. The value /a=b keeps its own =, because partition only cuts once. A plain split("=") would have produced three parts and broken the two-name unpacking.
Choosing between partition, split with maxsplit, and find
| Need | Best tool | Reason |
|---|---|---|
| Cut once at the first or last separator, and know if it matched | `partition` / `rpartition` | Fixed three-item result |
| Several fields from one separator | `split` | Returns every field |
| Cut once, but split on whitespace runs | `split(None, 1)` | `partition` cannot do whitespace runs |
| Only need to know whether a substring exists | `in` | No tuple to build |
| Cut on a pattern such as `[,;]` | `re.split` | `partition` matches a literal string only |
| Quoted fields or nested structure | the `csv` module or a real parser | The separator can occur inside data |
Use partition when the data has a clear "first one wins" or "last one wins" rule. Use split when the number of fields is part of the data.
Summary of behavior
partition(sep)cuts at the first match andrpartition(sep)at the last.- Both return a 3-tuple
(before, sep, after). - If
sepis not found,partitionreturns(s, '', '')andrpartitionreturns('', '', s). - An empty
sepraisesValueError, and a non-stringsepraisesTypeError. - Test the middle item to learn whether the separator matched. Do not test the other two.
Exercise
What do "a=b=c".partition("="), "a=b=c".rpartition("=") and "abc".rpartition("=") return?
Show answer
"a=b=c".partition("=") returns ('a', '=', 'b=c'), because it cuts at the first "=". "a=b=c".rpartition("=") returns ('a=b', '=', 'c'), because it cuts at the last "=". "abc".rpartition("=") returns ('', '', 'abc'), because with no separator found, rpartition puts the whole string in the last slot.
Exercise
A function receives strings such as "example.com:8080" and "example.com". It must return the host and the port as an int, or None for the port when no colon is present. Which method would you use, and how do you decide whether a port was given? Name one input that this approach handles incorrectly.
Show answer
Use rpartition(":") so the cut happens at the last colon: host, sep, port = text.rpartition(":"). A port was given only if sep is non-empty. If sep is empty, the host is the whole text, which rpartition puts in the last slot, so return (text, None). If sep is non-empty, return (host, int(port)). It handles a bare IPv6 address such as "::1" incorrectly, because the last colon is part of the address, not a port separator. It also fails with ValueError from int() on "example.com:" because the port text is empty. A real parser, such as urllib.parse.urlsplit with a "//" prefix, handles these inputs.
Exercise
Why does key, value = "timeout".split("=", 1) raise an error while key, sep, value = "timeout".partition("=") does not? What does the second line leave in value?
Show answer
split returns a list with one item ['timeout'] when the separator is missing, so unpacking into two names raises ValueError (not enough values to unpack). partition always returns three items, here ('timeout', '', ''), so unpacking succeeds. value is the empty string, and sep is also the empty string, which tells you the separator was not found.