Python String partition()
Method
The partition() method in Python is used to split a string into three parts using a specified separator. It always returns a tuple of 3 elements.
Syntax
string.partition(separator)
Parameters:
separator
– The string to search for (must not be empty).
Returns:
- A tuple of 3 parts:
(before_separator, separator, after_separator)
- If the separator is not found, the first item will be the entire string, and the second and third will be empty strings.
Example: Basic Usage
text = "python-is-awesome"
result = text.partition("-")
print(result)
('python', '-', 'is-awesome')
Why? Because:
'python'
comes before the first'-'
'-'
is the separator'is-awesome'
comes after
Example: Separator Not Found
text = "learnpython"
result = text.partition(" ")
print(result)
('learnpython', '', '')
The separator (a space) was not found, so the whole string is returned as the first element.
Real-world Use Case
You can use partition()
when you want to break a string into 2 parts at the first occurrence of a keyword or symbol. For example:
email = "user@example.com"
username, sep, domain = email.partition("@")
print("Username:", username)
print("Domain:", domain)
Username: user
Domain: example.com
Comparison with split()
partition()
splits at the first occurrence only.split()
can split multiple times and returns a list.
Common Mistakes
- Using an empty string as the separator → causes a
ValueError
- Expecting more than 3 values in the returned tuple
Interview Tip
If you're asked to extract a prefix or postfix around a delimiter in a string, partition()
is the fastest and cleanest method to use.
Summary
partition()
splits a string into 3 parts using a separator.- Returns a tuple:
(before, separator, after)
- Helpful for quick parsing and string analysis.
Practice Problem
Write a Python program that reads a string like "title:Introduction to Python"
and splits it into label and value using partition()
.
text = "title:Introduction to Python"
label, sep, value = text.partition(":")
print("Label:", label)
print("Value:", value)
Label: title
Value: Introduction to Python