Python String partition() Method

The partition() method splits a string into three parts based on a specified separator and returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

Syntax

string.partition(separator)

Parameter

separator (required): The string at which the partition occurs.

Return Value

Returns a tuple with three elements:

(1) The part of the string before the separator.

(2) The separator itself (if found).

(3) The part of the string after the separator.

If the separator is not found, it returns a tuple containing the original string and two empty strings.

Examples

Partitioning a String at a Specific Substring

text = "python is easy and awesome"
result = text.partition("is")
print(result) # Output: ('python ', 'is', ' easy and awesome')

Separator Not Found

If the separator is not found in the string, the partititon() method will return a tuple containing the original string followed by two empty strings.

text = "python is awesome"
result = text.partition("and")
print(result) # Output: ('python is awesome', '', '')

Multiple Occurrences of the Separator

If the separator appears more than once in the string, the partition() method splits the string at the first occurrence of the separator from the left.

text = "chicken,banana,apple"
result = text.partition(",")
print(result) # Output: ('chicken', ',', 'banana,apple')

partition() vs split() Method

Both partiton() and split() are string methods used to divide strings, but they have key differences in behavior and use cases. Here is table containing the most important ones:

Featurepartition()split()
Splitting Only splits the string at the first occurrence of the separator.Splits the string at every occurrence of the separator.
Return TypeAlways returns a 3-element tuple.Returns a list of substrings.
SeparatorIncludes a separator in the results.Does not include a separator in the results.