Python str.partition() function
In Python, the str.partition()
method is used to split a string into three parts based on a specified separator. This method searches for the first occurrence of the separator and splits the string into a tuple containing three elements: the part before the separator, the separator itself, and the part after the separator.
Syntax
- separator: The string that you want to use as the delimiter to split the original string.
Return Value
The method returns a tuple with three elements:
- The part of the string before the separator.
- The separator itself.
- The part of the string after the separator.
If the separator is not found in the string, the first element of the tuple will be the original string, and the second and third elements will be empty strings.
Example Usage
- Basic usage:
- Separator not found:
If the separator is not present in the string, the entire string is returned as the first element of the tuple, with the other two elements being empty:
- Multiple occurrences of the separator:
The partition()
method only splits at the first occurrence of the separator:
- Using an empty separator:
If an empty string is passed as the separator, the behavior is different from what one might expect. It splits the string between each character:
Summary
- Use
str.partition()
to split a string into three parts based on a specified 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 original string is returned as the first element, with the other two elements being empty strings.
- This method is useful for parsing strings where you need to separate a specific delimiter and retain both the delimiter and the surrounding text.