Skip to main content

Python String partition() Function

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
note

Note that:

  • partition() method splits the string at the first occurrence of the separator
  • rpartition() method splits the string at the last occurrence of the separator

If there is only one occurrence of the separator, both methods work exactly the same.

Syntax

my_string.partition(separator)

partition() Parameters

Python String partition() function parameters:

ParameterConditionDescription
separatorRequiredAny substring to split the string with.

partition() Return Value

Python String partition() function returns a tuple of three elements containing:

  • if the separator parameter is found in the string
    • the part before the separator
    • the separator parameter
    • the part after the separator
  • if the separator parameter is not found in the string
    • the string itself and two empty strings

Examples

Example 1: Partition of a String with partition()

The partition() function 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')