str.partition()
Splits a string at the first match of a separator and returns a tuple of three: the part before, the separator, the part after.
str.partition(sep)partition() cuts a string once, at the first place where sep appears, and always gives back exactly three strings: what came before, the separator itself, and what came after.
Because the result always has three parts, you can unpack it safely: key, _, value = line.partition("="). With str.split() you would have to check how many pieces you got.
If the separator is not found, there is no error: you get the whole string followed by two empty strings. Check the middle part to know whether the cut happened. Its twin rpartition() cuts at the last match instead.
Parameters
| Parameter | What it is |
|---|---|
seprequired | The separator to cut at. Must not be empty. |
Return value
A tuple of three strings: (before, sep, after). If sep is not found: (whole_string, "", "").
Examples
1Cut at the first separator
print("key=value".partition("="))
print("a=b=c".partition("="))('key', '=', 'value')
('a', '=', 'b=c')2Read settings lines
lines = ["theme=dark", "size = 14", "debug"]
for line in lines:
key, sep, value = line.partition("=")
if sep:
print(key.strip(), "->", value.strip())
else:
print(key, "has no value")theme -> dark size -> 14 debug has no value
An empty sep part means the separator was missing.
3Separator not found
print("hello".partition(":"))('hello', '', '')4Cut at the last match with rpartition()
name = "archive.tar.gz"
print(name.partition("."))
print(name.rpartition("."))('archive', '.', 'tar.gz')
('archive.tar', '.', 'gz')5Split an e-mail address
user, _, domain = "[email protected]".partition("@")
print(user)
print(domain)omar mail.example
_ is the usual name for a part you do not need.
Common mistakes
Forgetting that a missing separator gives the whole string first
When the separator is missing, the text lands in the first part. If you only read the last part, you get an empty string without noticing.
line = "no colon here"
before, sep, after = line.partition(":")
print(repr(after))
print(repr(before))'' 'no colon here'
Questions people ask
partition() vs split(): which should I use?
partition() for one cut with a fixed result shape; str.split() when you want all the pieces or a list.
How do I split at the last separator?
Use rpartition(), or rsplit(sep, 1).
What happens with an empty separator?
Python raises ValueError, as with split("").