Python Tutorial Python Advanced Python References Python Libraries

Python String - partition() Method



The Python partition() method is used to create three partition of the string and returns them in tuple form. The three elements of tuple will be: portion of the string before first occurrence of the specified character(s), the specified character and remaining portion of the string after first occurrence of the specified character(s).

Syntax

string.partition(characters)

Parameters

characters Required. specify character(s) which need to be searched in the string.

Return Value

Returns a tuple which contains three elements as a result of partition of the given string.

Example:

In the example below, partition() method is used to create three partition of the string and returns them in tuple form.

MyString = "Python#Java#C++"
print(MyString.partition("#"))

The output of the above code will be:

('Python', '#', 'Java#C++')

Example:

If the specified character(s) is not present in the string then the three elements of tuple will be: the whole string, ' ' and ' '.

MyString = "Python#Java#C++"
print(MyString.partition("Javascript"))

The output of the above code will be:

('Python#Java#C++', '', '')

❮ Python String Methods