What is the string.partition() method in python?
The partition method will split the first occurrence of string_B in string_A and returns a tuple with three items.
-
The first item contains the part of a string the before
string_B. -
The second item contains the
string_Bitself. -
The third item contains the part of the string after the
string_B.
If the string_B is not present in a string, then a tuple with the string_A and two empty strings is returned. That is, (string_A, '', '') is returned.
Syntax
string_A.partition(string_B)
Code
Example 1
string = "this test is a test"tup = string.partition('test')print(tup)
Explanation 1
In the cobe above, we created a string this test is a test and called partition('test'). This will split the string at the first occurrence of the substring test and return a tuple containing three items.
-
First item: Part of the string before the first occurrence of
testsubstring. In our case, it isthis. -
Second item: Separator string itself. In our case, it is a
test. -
Third item: Part of the string after the first occurrence of
testsubstring. In our case, it is" is a test".
Example 2
string = "this test is a test"tup = string.partition('best')print(tup)
Explanation 2
In the example above, we created a string this test is a test and called partition('best'), but the string has no substring best, so the partition method will return a tuple containing three items.
-
First item: Source string. In our case,
this test is a test. -
Second and third items: Empty string.