partition() looks for a separator, and cuts the string at its first appearance. It always returns a tuple of exactly three items: the part before, the separator itself, and the part after.
If the separator is not found, you still get three items: the whole string, then two empty strings. That fixed size makes it easy to unpack into three variables, and the middle item tells you whether the separator was found. The original string is not changed.
text.partition() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the separator to look for. It is required, and it must be a string.
python
before, sep, after = text.partition(sep)
Call
What it does
"key=value".partition("=")
Returns ('key', '=', 'value'). The text is cut at the equals sign.
"key=a=b".partition("=")
Returns ('key', '=', 'a=b'). Only the first equals sign is used.
"novalue".partition("=")
Returns ('novalue', '', ''). The separator is missing, so the whole text is the first item.
To cut at the last separator use rpartition(). To get a list and cut at every separator, use split(). To only find where the separator is, use find().
Library declarations
python
str.partition(sep) -> tuple
# returns: (before, sep, after), a tuple of three strings
Parameters
Parameter
Description
sep
Required. The text to split at. It must be a non-empty string, otherwise ValueError is raised.
Return Value
Return Value
Description
tuple
A tuple of three strings: the part before the first separator, the separator, and the part after. If the separator is not found, it is (text, '', '').
Python Examples
Example 1 — Split a Name and a Value
Unpack the three items into variables, then look at the tuple itself.
Cut at the at sign. The user name goes into user, and the rest goes into domain.
An unused separator. The variable at holds the @ sign, and it is not needed any more.
Chain a second cut.domain.partition(".")[0] takes the part before the first dot, which is mail.
Frequently Asked Questions
It splits a string at the first occurrence of a separator and returns a tuple of three strings: the part before, the separator, and the part after.
It returns a tuple with the whole string first, followed by two empty strings.
partition() cuts once and always returns three items, including the separator. split() cuts at every separator by default and returns a list without the separators.
partition() uses the first separator, and rpartition() uses the last one. Both return three items.
Yes. The separator can be any non-empty string, for example "text".partition("::").