Meaning
Returns a 3-tuple (before, sep, after) splitting the string at the first occurrence of the separator. Eliminates the need for separate find-and-slice operations when you need both sides of a delimiter. Reach for it when parsing structured text where the separator itself carries meaning, such as key=value pairs or URI schemes.
Primary Function
String manipulation
Communicative Purpose
Enables splitting a string into three parts around the first occurrence of a separator without repeated searching.
Pattern
text.partition(separator)
Core Structure
... .partition(...)
Função primária
String manipulation
Propósito comunicativo
Enables splitting a string into three parts around the first occurrence of a separator without repeated searching.
Situações de gatilho
Configuration parsing: splitting key=value lines while preserving the delimiter; URL processing: separating scheme from authority at '://'; Protocol parsing: extracting command from payload at the first space
Contextos
Text processing scripts, data cleaning, configuration parsing.
Padrão
text.partition(separator)
Estrutura central
... .partition(...)
Slots de substituição
text: str, separator: str
Colocados típicos
- unpacking into three variables
- used with if-else to check if separator found.
Substituições comuns
- using split with maxsplit=1 and handling resulting list length
- or using find and slicing.
Erros comuns
confusing partition with split (which returns list), expecting two return values, forgetting that the separator itself is included in the middle tuple element.
Similar / contraste
str.split(sep, maxsplit=1) returns list of up to two parts; str.find returns index of first occurrence.
Interferências
Coming from languages lacking a built-in partition method (e.g., JavaScript), developers may manually implement with indexOf and slice, leading to more verbose code.
Família do chunk
- str.split
- str.rpartition
- str.partition
- str.removeprefix
- str.removesuffix
Nuance
Avoid when you need all occurrences split (use split instead) or when you only need the index (use find). Runs in O(n) time scanning left to right. When the separator is not found, the entire string lands in the first element with empty strings for the other two — code that only checks the middle element can silently treat 'not found' as 'found empty'.
Efeito pragmático
Enables clean extraction of prefix, separator, and suffix in a single step without repeated searching.
Dica de memória
Like slicing a sandwich at the first pickle — you always get three pieces: bread before, pickle, bread after.
Nota
The method runs in O(n) time and always returns a tuple of three strings.
Upgrade path
Using regular expressions for more complex, conditional splitting.
Log in to save chunks.