The Python partition is one of the String Methods, which is useful to split the given string using the specified separator and return a tuple with three arguments. This Python partition function starts looking for the separator from the Left-Hand side. Once it finds the separator, it returns the string before the Separator as Tuple Item 1, Separator itself as Tuple Item 2, and the remaining sentence (or after the Separator) as Tuple Item 3.
The syntax of the partition in Python Programming Language is
Separator: This argument is required, and if you forget this argument, python throw TypeError. If you pass the non-existing item as a separator, the partition function returns the whole string as Tuple Item 1 followed by two empty tuple items.
Return Value: It returns Tuple with three arguments. For example, If we have A*B*C and If we use * as a separator. The Python partition function search for * from left to right. Once it finds * it returns the text before the * symbol as Tuple Item 1 (A), * as Tuple Item 2, and the remaining text as Tuple Item 3 (B*C).
Even though there are multiple occurrences of the separator, the Python partition string function looks for the first occurrence.
Python partition method Example
The following set of examples help to understand the string partition in Python Programming Language.
Str1 = 'Tutorial Gateway' Str2 = 'Learn-Python-Programming' Str3 = 'email@example.com' Str4 = Str1.partition(' ') print("After Partitioning String 1 = ", Str4) Str5 = Str2.partition('-') print("After Partitioning String 2 = ", Str5) Str6 = Str3.partition('@') print("After Partitioning String 3 = ", Str6) #Performing directly Str7 = 'First_Image.png'.partition('.') print("After Partitioning String 7 = ", Str7)
In this example, first, we declared three String variable Str1, Str2, Str3. Next, we assigned the corresponding value using the following statement.
Str1 = 'Tutorial Gateway' Str2 = 'Learn-Python-Programming' Str3 = 'firstname.lastname@example.org'
The following statement splits the Str1 into multiple parts based on the separator we specified (i.e., Empty Space) and prints the output.
Str4 = Str1.partition(' ')
It separates the Str2 into multiple parts based on the ‘_’ symbol and prints the output.
Str5 = Str2.partition('-')
The following Python statement partition the Str3 string into multiple parts based on the ‘@’ symbol and prints the output.
Str6 = Str3.partition('@')
The below code uses directly on String.
Str7 = 'First_Image.png'.partition('.')
Str8 = Str1.partition('*')