String partition() Method in Python

Python String partition() Method

The partition() method in Python is a string method that splits a string at the first occurrence of a specified separator and returns a tuple containing three elements:

  • The part of the string before the separator.
  • The separator itself.
  • The part of the string after the separator.

The syntax for using the partition() method is as follows:

string.partition(separator)

Parameters:

  • separator: The string value at which the original string will be split. It can be any substring present in the original string.

Return Value:

  • The method returns a tuple containing three elements: the part of the string before the first occurrence of the separator, the separator itself, and the part of the string after the separator.

Here's an example of how to use the partition() method:

sentence = "I love Python programming and Python is fun to learn"
separator = "Python"

result = sentence.partition(separator)

print(result)

Output:

('I love ', 'Python', ' programming and Python is fun to learn')

In this example, the partition() method splits the sentence at the first occurrence of the word "Python" and returns a tuple with three elements. The first element is the part of the string before "Python," the second element is the separator "Python" itself, and the third element is the part of the string after "Python."