Python String partition() Method

Last Updated : 31 Jan, 2026

partition() method splits a string into three parts at the first occurrence of a specified separator, returning a tuple containing the part before the separator, the separator itself, and the part after the separator. For Example:

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

Output
('Geeks ', 'for', ' Geeks')

Explanation: partition("for") splits the string 's' at the first occurrence of "for". It returns a tuple with three parts:

  • Part before the separator: 'Geeks '
  • The separator itself: 'for'
  • Part after the separator: ' Geeks'

Syntax

string.partition(separator)

Parameters: separator(required): a substring that separates the string

Return Type:

  • Returns a tuple of three strings: (before_separator, separator, after_separator).
  • If the separator is not found, the tuple returned is (string, '', '').

Examples of partition() Method

Example 1: This example demonstrates using partition() with a valid separator when the separator exists in the string.

Python
s = "Python is fun"

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

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

Explanation:

  • string is split at the first occurrence of the separator "is".
  • the method returns a tuple containing the three parts of the string.

Example 2: 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:

  • Since the separator "Java" is not present in the string, the entire string is returned as the first element of the tuple.
  • The second and third elements are empty strings.

Example 3: In case there are multiple seperators present in the string - the partition() method only splits at the first occurrence of the separator.

Python
s = "Learn Python with GeeksforGeeks with"
res = s.partition("with")
print(res)

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

Explanation:

  • string is split at the first occurrence of "with".
  • subsequent occurrences of the separator are ignored by the partition() method.

Example 4: partition() method works seamlessly with special characters:

Python
s = "key:value"

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

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

Explanation:

  • string is split into three parts at the occurrence of ":"
  • this method is particularly useful when parsing key-value pairs in a structured format.

Also read: tuple, strings, delimeter.

Comment

Explore