str.partition()
str.partition(sep) tuple[str, str, str] · Added in v3.x · Updated March 13, 2026 · String Methods The .partition() method splits a string into three parts using a separator. It returns a tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, the tuple contains the original string followed by two empty strings.
Syntax
str.partition(sep)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| sep | str | — | The separator string to split on |
Return Value
Returns a tuple of three strings: (before_sep, sep, after_sep). If the separator is not found, returns (original_string, ”, ”).
Examples
Basic usage
text = "hello world"
result = text.partition(" ")
print(result)
# ('hello', 'world')
The separator is included in the result as the middle element.
Separator not found
text = "hello"
result = text.partition(" ")
print(result)
# ('hello', '', '')
When the separator doesn’t exist, the entire string becomes the first element.
Using with delimiters
url = "user@example.com"
result = url.partition("@")
print(result)
# ('user', '@', 'example.com')
This is useful for parsing email addresses or similar delimited data.
Extracting parts
timestamp = "2024-01-15"
date, sep, time = timestamp.partition("-")
print(date)
# 2024
print(time)
# 01-15
You can unpack the result directly into three variables.
Common Patterns
Safe parsing with fallback
def extract_domain(email):
user, sep, domain = email.partition("@")
if sep:
return domain
return "No domain"
print(extract_domain("user@example.com"))
# example.com
print(extract_domain("invalid"))
# No domain
This pattern avoids exceptions when the separator doesn’t exist.
Conditional processing
def process_input(value):
key, sep, val = value.partition("=")
if sep:
return {key: val}
return {"data": value}
print(process_input("name=Alice"))
# {'name': 'Alice'}
print(process_input("novalue"))
# {'data': 'novalue'}
Header parsing
header = "Content-Type: application/json"
name, sep, value = header.partition(": ")
print(name)
# Content-Type
print(value)
# application/json
Works well for parsing HTTP-style headers.
Difference from split()
The .partition() method always returns exactly three elements, making it useful when you need predictable unpacking. The .split() method returns a list of varying length:
# partition always returns 3 elements
"a-b-c".partition("-")
# ('a', '-', 'b-c')
# split returns list of varying length
"a-b-c".split("-")
# ['a', 'b', 'c']
"a b c".split(" ")
# ['a', 'b', 'c']