Python String partition() Method

Short answer
str.partition(sep) splits a string at the first occurrence of sep and always returns a tuple of three parts: the text before, the separator itself, and the text after.

partition() is perfect for text with exactly one meaningful split point, such as key=value, user@domain or name: value. Unlike split(), it always gives you three items, so you can unpack them with tuple unpacking without worrying about how many pieces there are. If the separator is missing, you still get three items, with empty strings in the last two. rpartition() does the same from the right-hand end.

Quick facts
Syntaxtext.partition(sep)
Parameterssep: a non-empty separator string
ReturnsA tuple (before, sep, after)
Separator missing(text, "", "")
Right-hand versiontext.rpartition(sep) splits at the last occurrence

How str.partition() returns three parts

Only the first separator is used. Everything after it, including later copies of the separator, stays together in the third item.

Python
print("key=value".partition("="))
print("a=b=c".partition("="))
print("novalue".partition("="))

What partition() returns when the separator is missing

No error is raised. The whole string comes back as the first item, and the other two are empty strings. This makes the empty separator item a reliable flag: if sep is empty, the separator was not found.

Python
before, sep, after = "settings".partition(":")
print(repr(before), repr(sep), repr(after))
print(bool(sep))

partition() vs split() vs rpartition()

MethodSplits atResult for `"a.b.c"` with `"."`Missing separator
partition(".")First separator('a', '.', 'b.c')('a.b.c', '', '')
rpartition(".")Last separator('a.b', '.', 'c')('', '', 'a.b.c')
split(".")Every separator['a', 'b', 'c']['a.b.c']
split(".", 1)First separator['a', 'b.c']['a.b.c']
rsplit(".", 1)Last separator['a.b', 'c']['a.b.c']

Examples you can run

Press Run, then edit the code and run it again.

Split a setting at the first equals sign

Unpack the three parts directly; the value keeps any later = signs.

Split a setting at the first equals sign
line = "url=https://example.com/?a=1"
key, sep, value = line.partition("=")
print(key)
print(value)
Expected outputurl
https://example.com/?a=1

Get the user name and domain of an email

The separator item can be ignored with _.

Get the user name and domain of an email
email = "asha@example.com"
user, _, domain = email.partition("@")
print(user)
print(domain)
Expected outputasha
example.com

Find a file extension with rpartition()

rpartition() splits at the last dot, so archive.tar.gz gives gz.

Find a file extension with rpartition()
name = "archive.tar.gz"
base, dot, ext = name.rpartition(".")
print(base)
print(ext)
Expected outputarchive.tar
gz

Detect a missing separator

An empty middle item means there was no separator in the text.

Detect a missing separator
for text in ["name: Asha", "just text"]:
    head, sep, tail = text.partition(": ")
    print(head, "|", tail if sep else "(no value)")
Expected outputname | Asha
just text | (no value)

Common mistakes

Unpacking into two variables

✗ Wrong

key, value = "a=1".partition("=")
ValueError: too many values to unpack (expected 2)

✓ Right

key, _, value = "a=1".partition("=")
print(key, value)

partition() returns three items. Keep the middle one, or ignore it with _.

Using an empty separator

✗ Wrong

print("abc".partition(""))
ValueError: empty separator

✓ Right

print(list("abc"))

Use a non-empty separator. To split into characters, use list(text).

Assuming a missing separator raises an error

✗ Wrong

before, sep, after = "abc".partition("-")
print(after.upper())
No error, but `after` is an empty string, so nothing useful is printed.

✓ Right

before, sep, after = "abc".partition("-")
if sep:
    print(after.upper())
else:
    print("no dash found")

Test the separator item before using the last part.

Python String partition() Method: questions people ask

What does partition() return in Python?

A tuple of three strings: the part before the first separator, the separator, and the part after it. If the separator is missing, you get the original string and two empty strings.

What is the difference between partition() and split()?

partition() splits once and always returns exactly three items, while split() returns a list and can split at every separator.

How do I split a string at the last occurrence of a character?

Use rpartition(), for example "a.b.c".rpartition(".") gives ('a.b', '.', 'c').

Keep learning

Step-by-step lessons:
Python StringsPython String MethodsPython Unpacking

Related:
Python String split() MethodPython String splitlines() MethodPython String find() MethodPython Tuples

More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →