Python String partition() Method

Example

Search for the word "bananas" and return a tuple containing three elements:

  • 1 - All content before the match
  • 2 - The match
  • 3 - All content after the match
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)

Run Instance

Definition and Usage

The partition() method searches for the specified string and splits it into a tuple containing three elements.

The first element contains the part of the string before the specified string.

The second element contains the specified string.

The third element contains the part of the string after the match.

Note: This method searches for the first occurrence of the specified string.

Syntax

string.partition(value)

Parameter Value

Parameter Description
value Required. The string to be retrieved.

More Examples

Example

If the specified value is not found, the partition() method will return a tuple containing: 1 - the entire string, 2 - an empty string, 3 - an empty string:

txt = "I could eat bananas all day"
x = txt.partition("apples")
print(x)

Run Instance