Python String partition()


Python String partition() method

Python String partition() method splits the string at the occurrence of specified separator, and returns a tuple containing the first string part before the split, separator, and the string part after the split.

Consider that given string is in x.

x = "apple-banana-cherry"

Then the return value of x.partition('-') is

('apple', '-', 'banana-cherry')

In this tutorial, you will learn the syntax and usage of String partition() method in Python language.

Syntax of partition() method

The syntax of String partition() method in Python is given below.

str.partition(sep)

Parameters

The string partition() method takes one mandatory parameter.

ParameterDescription
sepRequired
A string value.
The separator using which the string is split into two parts.

Return value

The string partition() method returns a tuple of length 3.

If the separator is not present in the string, then the returned tuple has the original string as first item, and the empty strings as second and third item.

Examples

1. Partition the string in Python

In this example, we take a string value in variable x. We have to partition this string with a separator "-".

Call partition() method on the string object x and pass the separator "-" as argument to the method.

Python Program

x = "apple-banana-cherry"

result = x.partition("-")
print(result)

Output

('apple', '-', 'banana-cherry')

2. partition() when separator is not present in the string

In the following program, we take a string value in variable x such that the separator "," is not present in the string, and observe the return value of the String partition() method.

Python Program

x = "apple-banana-cherry"

result = x.partition(",")
print(result)

Output

('apple-banana-cherry', '', '')

Summary

In this tutorial of Python String Methods, we learned about String partition() method, its syntax, and examples.