How to Use partition() Method in Python String
In Python, the
partition() method splits a string into three parts using a specified separator: the part before the separator, the separator itself, and the part after. It returns a tuple with these three parts, or the original string and two empty strings if the separator is not found.Syntax
The partition() method is called on a string and takes one argument: the separator string to split on.
- string.partition(separator)
It returns a tuple of three elements:
- Part before the separator
- The separator itself
- Part after the separator
python
result = 'hello world'.partition(' ') print(result)
Output
('hello', ' ', 'world')
Example
This example shows how to split a sentence into three parts using a comma as the separator. It prints the tuple with the part before the comma, the comma itself, and the part after.
python
sentence = 'apple,banana,cherry' result = sentence.partition(',') print(result) # When separator is not found result2 = sentence.partition(';') print(result2)
Output
('apple', ',', 'banana,cherry')
('apple,banana,cherry', '', '')
Common Pitfalls
One common mistake is expecting partition() to split the string into multiple parts like split(). It only splits once at the first occurrence of the separator.
Also, if the separator is not found, it returns the original string and two empty strings, which can be confusing if not handled.
python
text = 'one-two-three' # Wrong: expecting multiple splits print(text.partition('-')) # Only splits at first '-' # Correct: use split() for multiple splits print(text.split('-'))
Output
('one', '-', 'two-three')
['one', 'two', 'three']
Quick Reference
- partition(separator): Splits string into 3 parts at first separator.
- Returns a tuple: (before, separator, after).
- If separator not found, returns (original_string, '', '').
- Only splits once, unlike
split().
Key Takeaways
Use
partition() to split a string into exactly three parts at the first separator.It returns a tuple: before separator, separator, and after separator.
If the separator is missing, the original string is returned with two empty strings.
For multiple splits, use
split() instead of partition().Remember
partition() always splits only once at the first occurrence.