Sub topic 6
Dividing at the first or last separator with partition
This chapter assumes you know how to call string methods, unpack tuples, and use str.split with a separator and maxsplit. It builds on the previous chapter on maxsplit and rsplit.
What partition does
str.partition(sep) finds the first occurrence of sep and returns a tuple of three strings: the text before it, the separator itself, and the text after it. str.rpartition(sep) does the same at the last occurrence.
print("[email protected]".partition("@")) # ('user', '@', 'example.com')
print("no-at-sign".partition("@")) # ('no-at-sign', '', '')
print("a.b.c".rpartition(".")) # ('a.b', '.', 'c')The result always has exactly three items, so you can unpack it safely:
head, sep, tail = "key=value=more".partition("=")
print(head) # key
print(sep) # =
print(tail) # value=moreWhen the separator is missing
If the separator does not occur, partition returns the whole string followed by two empty strings. rpartition returns two empty strings followed by the whole string. The whole string moves to the other end, which matters when you read the result.
print("no-at-sign".partition("@")) # ('no-at-sign', '', '')
print("README".rpartition(".")) # ('', '', 'README')The middle item tells you whether the separator was found. An empty separator is never a valid match, so an empty middle item always means "not found". You can test it with if not sep:.
Partition versus split with maxsplit
"key=value".split("=", 1) looks similar, but its result length varies. With no separator it returns a one-item list, and unpacking that into two names raises ValueError.
| Call on `"novalue"` | Result | Unpacking into two names |
|---|---|---|
| `split("=", 1)` | `['novalue']` | Raises `ValueError` |
| `partition("=")` | `('novalue', '', '')` | Needs three names, always works |
Use partition when you always want a fixed shape and need to detect a missing separator. Use split when you want a list, or when there may be many separators.
A worked example: parsing settings lines
Each line should look like name = value. The value may contain more = characters, such as a URL with a query string. partition splits only at the first one, so the value stays intact.
def parse_setting(line):
key, sep, value = line.partition("=")
if not sep:
return None
return key.strip(), value.strip()
print(parse_setting("timeout = 30")) # ('timeout', '30')
print(parse_setting("# just a comment")) # None
print(parse_setting("url = http://x.org?a=b")) # ('url', 'http://x.org?a=b')The function never needs a try block or a length check. The sep item answers the question "was there an equals sign?".
Splitting off the last component
rpartition is the natural tool for file extensions and the last part of a dotted name:
name, dot, ext = "archive.tar.gz".rpartition(".")
print(name) # archive.tar
print(ext) # gz
name, dot, ext = "README".rpartition(".")
print(repr(name), repr(ext)) # '' 'README'The second case is a common bug. A file with no dot ends up with the whole name in ext. Check dot before trusting ext. For real file paths, os.path.splitext or pathlib.Path.suffix also handles cases like hidden files such as .bashrc.
Details and limits
- The separator can be longer than one character:
"a::b".partition("::")gives('a', '::', 'b'). - An empty separator raises
ValueError: empty separator. - The separator is a literal string, not a pattern. For patterns, use
re.split(covered later in this tutorial). - Strings are immutable, so
partitionreturns new strings and leaves the original unchanged. - You can ignore parts you do not need with the conventional name
_:user, _, domain = email.partition("@").
Exercises
Exercise
What does "a-b-c".rpartition("-") return, and what does "abc".rpartition("-") return?
Show answer
The first returns ('a-b', '-', 'c') because rpartition splits at the last separator. The second returns ('', '', 'abc'), because with no separator the whole string goes into the last item and the other two are empty.
Exercise
Write a function hostandport(text) that takes "example.org:8080" and returns ("example.org", "8080"). If there is no colon, it should return (text, None). Which method fits, and why?
Show answer
Use partition. def hostandport(text): host, sep, port = text.partition(":") return (host, port) if sep else (text, None) partition always returns three items and the middle item shows whether the colon was found, so no length check or exception handling is needed.