Python String partition()

Python String.partition() is used to partition this string into three parts. The partition() method takes a value as argument, searches for it, and if found, splits the string at this value, and returns the part before this value as first, part, this value as second part, and the rest of the string as third part. These splits are returned in a tuple.

In this tutorial, we will learn the syntax and examples for partition() method of String class.

Syntax

The syntax to call partition() method on string x in Python is

x.partition(value)

where

ParameterRequired / OptionalDescription
valueRequiredA string. Specifies the value at which the string has to be split.
ADVERTISEMENT

Examples

In the following program, we take a string 'hello world apple banana', and partition this string at value='world'.

Example.py

x = 'hello world apple banana'
result = x.partition('world')
print('Original String  : ', x)
print('Partitions : ', result)
Try Online

Output

Original String  :  hello world apple banana
Partitions :  ('hello ', 'world', ' apple banana')

If the given argument is not present in the string, then the first item of resulting tuple is the original string, second and third parts are empty.

Example.py

x = 'hello world apple banana'
result = x.partition('cherry')
print('Original String  : ', x)
print('Partitions : ', result)
Try Online

Output

Original String  :  hello world apple banana
Partitions :  ('hello world apple banana', '', '')

Conclusion

In this Python Tutorial, we learned how to split a string into partitions using partition() method, with examples.