Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.partition() method

Reference for Python str.partition(): split a string at the first occurrence of a separator into a 3-tuple of head, separator and tail, with no exceptions.

The str.partition() method searches a string for the first occurrence of a separator and returns a tuple of three strings: the part before the separator, the separator itself, and the part after it. The result always has exactly three items, so you can unpack it safely.

If the separator is not found, you get the whole string followed by two empty strings. That makes partition() a good fit for "split once" jobs such as key=value pairs, where a missing separator is a normal case and not an error.

Python
head, sep, tail = "[email protected]".partition("@")
print(head, sep, tail)   # user @ example.com

Try it

Python Splitting key=value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Checking whether the separator was found

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.partition(sep)
Name Description
sep The separator to search for. It must be a non-empty string.

Return value: a tuple (before, sep, after). If sep is not found, the tuple is (original_string, "", "").

Raises: ValueError ("empty separator") if sep is an empty string; TypeError if sep is not a string.

Usage notes

  • Only the first match counts. Everything after the first separator, including further separators, stays together in the third item. Use rpartition() to split at the last one.
  • Always three items. Unlike split(), the length never changes, so a, b, c = s.partition(x) cannot fail with "not enough values".
  • Detect a miss by testing the middle item: it is empty exactly when the separator was not found.
  • Separator is a literal string, not a pattern and not a set of characters. For patterns use the re module.
  • Cheaper than split(sep, 1) when the result is unpacked, and it never raises on a missing separator.
  • Also exists for bytes and bytearray, with bytes arguments.