The String partition() method splits the string at the first occurrence of the separator and returns a tuple containing three elements:
- The part of the string before the separator
- The separator itself
- The part of the string after the separator
Syntax
my_string.partition(separator)partition() Parameters
Python String partition() method parameters:
| Parameter | Condition | Description |
|---|---|---|
separator |
Required | Any substring to split the string with. |
partition() Return Value
Python String partition() method returns a tuple of three elements containing:
- if the
separatorparameter is found in the string- the part before the separator
- the separator parameter
- the part after the separator
- if the
separatorparameter is not found in the string- the string itself and two empty strings
Examples
Example 1: Partition of a String with partition()
The partition() method returns a tuple of three elements.
In this example, the separator 'for' is found, and so a tuple made of the part before the separator, the separator and the part after the separator is returned:
my_str = 'This is an example for partition() method'
result = my_str.partition('for')
print(result) # Output: ('This is an example ', 'for', ' partition() method')output
('This is an example ', 'for', ' partition() method')Example 2: Partition of a String when Separator is Not Found
If the separator is not found, the method returns a tuple containing the string itself, followed by two empty strings.
my_str = 'This is an example for partition() method'
result = my_str.partition('and')
print(result) # Output: ('This is an example for partition() method', '', '')output
('This is an example for partition() method', '', '')Example 3: Partition of a String when Multiple Occurrences of Separator are present
If the separator is present multiple times, the method splits the string at the first occurrence.
my_str = 'This is an example for partition() method'
result = my_str.partition('is')
print(result) # Output: ('Th', 'is', ' is an example for partition() method')output
('Th', 'is', ' is an example for partition() method')