Python String partition() Method - Explained with examples

The string partition() method in Python allows splitting the string at the specified location. It will return a new string with 3 parts: before the split position, at the split position, after the split position, and the positions are separated by ",". The specified position is treated as an argument. 

Here at LinuxAPT, we shall look into how to use the partition() method in Python.


More about the String partition() Method

The partition() method is used to split a string into 3 parts according to the specified position:

  • Part 1: before the split position.
  • Part 2: at the split position.
  • Part 3: after the split position.


What is the syntax of the String partition() Method ?

It is given below:

string.partition(value)

String partition() Method Parameter Values:

value: the position you want to split


Examples of using String partition() Method

1. Take a look at the below function:

txt = "I wanna eat an apple"
x = txt.partition("eat")
print(x)

The Output will give:

('I wanna', 'eat', 'an apple')


2. The basic partition() method:

txt = "I wanna eat a banana"
x = txt.partition("eat")
print(x)

The Output will give:

('I wanna', 'eat', 'a banana')


3. The method did not find the specified location:

txt = "I wanna eat a banana"
x = txt.partition("cherry")
print(x)

The Output will give:

('I wanna eat a banana', ",")

It will print out the original string and 2 empty strings.


[Need help in fixing Python function issues ? We can help you. ]

This article covers the usage of the partition() method in Python. In fact, Python partition() function is used to partition a string at the first occurrence of the given string and return a tuple that includes 3 parts – the part before the separator, the argument string (separator itself), and the part after the separator.


Python partition() function partition() Parameters

The partition() function accepts a single parameter:

  • separator – a string parameter that separates the string at the first occurrence of it.
  • Note – If the separator argument is kept empty, then the Python interpreter will throw a TypeError exception.

Related Posts