Tutorial Study Image

Python partition()

The partition() function in python helps to divide the string as a tuple. It first finds out the string and split into tuple having three parts. This first part contains part before the specified string, the second part contains specified string and the third part contains part after the given string.


string.partition(separator) #where separator can be numbers as well as symbols
 

partition() Parameters:

The partition() function takes single parameter. This method searches the first occurrence of the given string. The search in the partition() is case-sensitive.

Parameter Description Required / Optional
separator The string to search for Required

partition() Return Value

The return value is a tuple. If the separator parameter is not found then, the string itself and two empty strings are returned. If we are passing an empty string as separator, then the method will throw ValueError.

Input Return Value
string 3-tuple

Examples of partition() method in Python

Example 1: How partition() works if the seperator is not found?


string1 = "Python programming languages"

string2 = string1.partition("java")

print(string2)
 

Output:


('Python programming languages', '', '')

Example 2: How partition() works if the seperator is found?


string1 = "Python programming languages"

string2 = string1.partition("programming")

print(string2)
 

Output:


('Python','programming','languages')

Example 3: How partition() works if the seperator is empty?


string1 = "Python programming languages"

string2 = string1.partition(" ")

print(string2)
 

Output:


('Python programming languages', '', '')
ValueError: empty separator