Python String Partition Method

In python, the string partition() method is useful to search for the specified string and split the given string into a tuple object with three elements based on the specified string.

 

The three elements in the tuple object will contain the following substring parts.

 

  • The first element will contain the substring before the specified string.
  • The second element will contain the specified string.
  • The third element will contain the substring after the specified string.

Following is the pictorial representation of string partition() method functionality in python.

 

Python string partition method example

 

If you observe the above diagram, we are searching for the "to" string in the given string "Welcome to Tutlane" using the partition function in python. The partition() method has returned the tuple object by splitting the specified string into three parts.

String Partition Method Syntax

Following is the syntax of defining a string partition method in python to search and split the given string into a tuple object with three elements.

 

string.partition(param)

The string partition() method will accept one string parameter to search for the specified substring in the given string.

String Partition Method Example

Following is the example of using the partition() function in python to search and split the given string.

 

str = "Welcome to Tutlane"
result = str.partition("to")
print(result);

If you observe the above example, we used the partition() function with one parameter to search for the specified string.

 

The above python partition method example will return the result as shown below.

 

('Welcome ', 'to', ' Tutlane')

If the specified string is not found in the given string, the string partition() method will return the tuple object with three elements.

 

  • Complete given string
  • Empty string
  • Empty string

Following is the example of the string partition() method in python.

 

str = "Welcome to Tutlane"
result = str.partition("test")
print(result);

The above python string partition() method example will return the result as shown below.

 

('Welcome to Tutlane', '', '')

This is how you can use the string partition method in python to search for the specified string and split the given string into a tuple object based on the specified string in python.