String method

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.

IntermediateEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
sep
required
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

Pythoneditable
print("key=value".partition("="))
print("a=b=c".partition("="))
Output
('key', '=', 'value')
('a', '=', 'b=c')

2Read settings lines

Pythoneditable
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")
Output
theme -> dark
size -> 14
debug has no value

An empty sep part means the separator was missing.

3Separator not found

Pythoneditable
print("hello".partition(":"))
Output
('hello', '', '')

4Cut at the last match with rpartition()

Pythoneditable
name = "archive.tar.gz"
print(name.partition("."))
print(name.rpartition("."))
Output
('archive', '.', 'tar.gz')
('archive.tar', '.', 'gz')

5Split an e-mail address

Pythoneditable
user, _, domain = "omar@mail.example".partition("@")
print(user)
print(domain)
Output
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.

Pythoneditable
line = "no colon here"
before, sep, after = line.partition(":")
print(repr(after))
print(repr(before))
Output
''
'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("").

Spotted a mistake on this page? Tell us