Skip to main content

partition()

The partition() method is a string method in Python that splits the string at the first occurrence of a specified separator and returns a tuple containing three elements: 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 of the tuple.

Parameter Values

Parameter Description
sep

The separator used to split the string.

Return Values

The partition() method returns a tuple (str) with three elements.

How to Use partition() in Python

Example 1:

The partition() method splits a string into a tuple containing the part before the specified separator, the separator itself, and the part after the separator. If the separator is not found, the tuple contains the original string and two empty strings.

sentence = 'Hello, world! How are you?' 
parts = sentence.partition(', ') 
print(parts) # Output: ('Hello', ', ', 'world! How are you?')
Example 2:

The partition() method works with different separators within the same string. It only splits the string once at the first occurrence of the specified separator.

text = 'Python,is,awesome' 
first_split = text.partition(',') 
print(first_split) # Output: ('Python', ',', 'is,awesome')
Example 3:

If the separator is not found in the string, the partition() method returns a tuple with the original string and two empty strings.

phrase = 'This is a sample phrase' 
split_result = phrase.partition(':') 
print(split_result) # Output: ('This is a sample phrase', '', '')