Python String partition() Method (original) (raw)

Last Updated : 02 Jan, 2025

In Python, the Stringpartition() method splits the string into three parts at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

Let’s understand with the help of an example:

Python `

s = "Geeks geeks"

res = s.partition("for") print(res)

`

Output

('Geeks geeks', '', '')

Explanation:

Table of Content

Syntax of partition() method

string.partition(separator)

**Parameters:

**Return Type:

Using partition() with a valid separator

This example demonstrates the behavior when the separator exists in the string:

Python `

s = "Python is fun"

res = s.partition("is") print(res)

`

Output

('Python ', 'is', ' fun')

Explanation:

When the separator is not found

If the separator is absent, the partition() method returns a specific result.

Python `

s = "Python is fun"

res = s.partition("Java") print(res)

`

Output

('Python is fun', '', '')

Explanation:

Working with multiple occurrences of the separator

partition() method only considers the first occurrence of the separator:

Python `

s = "Learn Python with GeeksforGeeks"

res = s.partition("Python") print(res)

`

Output

('Learn ', 'Python', ' with GeeksforGeeks')

Explanation:

Using special characters as the separator

partition() method works seamlessly with special characters:

Python `

s = "key:value"

res = s.partition(":") print(res)

`

Output

('key', ':', 'value')

Explanation: