Python String partition() Method

Splits the string into a three-part tuple

Usage

The partition() method splits the string at the first occurrence of separator, and returns a tuple containing three items.

  • The part before the separator
  • The separator itself
  • The part after the separator

partition() Vs rpartition()

Unlike partition(), The rpartition() method splits the string at the last occurrence of separator.

Otherwise, both methods work exactly the same.

Syntax

string.partition(separator)

Python string partition() method parameters
ParameterConditionDescription
separatorRequiredAny substring to split the sting with.

Basic Example

Example: Split the string on ‘and’

S = 'Do it now and keep it simple'
x = S.partition('and')
print(x)    # ('Do it now ', 'and', ' keep it simple')

No Match Found

If the separator is not found, the method returns a tuple containing the string itself, followed by two empty strings.

Example: If the separator is not found

S = 'Do it now and keep it simple'
x = S.partition('or')
print(x)    # ('Do it now and keep it simple', '', '')

Multiple Matches

If the separator is present multiple times, the method splits the string at the first occurrence.

Example: Split the string at the first occurrence of ‘it’

S = 'Do it now and keep it simple'
x = S.partition('it')
print(x)    # ('Do ', 'it', ' now and keep it simple')