Python String partition() Method
Last Updated :
03 Oct, 2025
In Python, the partition() method is a handy tool when we need to split a string into exactly three parts based on the first occurrence of a given separator.
It returns a tuple containing:
- The part before the separator
- The separator itself
- The part after the separator
This is especially useful when we're parsing strings like filenames, email addresses, key-value pairs, or structured messages where we're expecting a predictable format with a known delimiter.
Let's understand with the help of an example:
Python
s = "Geeks for Geeks"
res = s.partition("for")
print(res)
Output('Geeks ', 'for', ' Geeks')
Explanation: partition("for") splits the string s at the first occurrence of "for". It returns a tuple with three parts:
- Part before the separator: 'Geeks '
- The separator itself: 'for'
- Part after the separator: ' Geeks'
Hence the output: ('Geeks ', 'for', ' Geeks')
Syntax
string.partition(separator)
Parameters:
- separator(required): a substring that separates the string
Return Type:
- Returns a tuple of three strings: (before_separator, separator, after_separator).
- If the separator is not found, the tuple returned is (string, '', '').
Examples of partition() Method
Example 1: Using partition() with a valid separator
This example demonstrates the behavior when the separator exists in the string:
Python
s = "Python is fun"
res = s.partition("is")
print(res)
Output('Python ', 'is', ' fun')
Explanation:
- string is split at the first occurrence of the separator "is".
- the method returns a tuple containing the three parts of the string.
Example 2: When the separator is not found
If the separator is absent, the partition() method returns a specific result.
Python
s = "Python is fun"
res = s.partition("Java")
print(res)
Output('Python is fun', '', '')
Explanation:
- Since the separator "Java" is not present in the string, the entire string is returned as the first element of the tuple.
- The second and third elements are empty strings.
Example 3: Working with multiple occurrences of the separator
partition() method only considers the first occurrence of the separator:
Python
s = "Learn Python with GeeksforGeeks"
res = s.partition("Python")
print(res)
Output('Learn ', 'Python', ' with GeeksforGeeks')
Explanation:
- string is split at the first occurrence of "Python".
- subsequent occurrences of the separator are ignored by the partition() method.
Example 4: Using special characters as the separator
partition() method works seamlessly with special characters:
Python
s = "key:value"
res = s.partition(":")
print(res)
Output('key', ':', 'value')
Explanation:
- string is split into three parts at the occurrence of ":".
- this method is particularly useful when parsing key-value pairs in a structured format.
Also read: tuple, strings, delimeter.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice