Python string partition() method
Python String partition() Method
Description
The partition() method splits a string at the first occurrence of a delimiter and returns a tuple of three strings: the portion before the delimiter, the delimiter itself, and the portion after the delimiter.
If the delimiter is not present, two empty strings are appended to the tuple. If the delimiter is an empty string, Python throws an error.
Syntax
var.partition(sep)
Parameters
- sep − The string to be used for partitioning.
Return Value
This method returns a tuple of three strings.
Example
var = 'Explicit is better than implicit'
var1 = var.partition('better')
print ("Original string:", var)
print ("Partition result:", var1)
var = "Explicit is better than implicit"
var2 = var.partition('Ex')
print ("Original string:", var)
print ("Partition result:", var2)
var = 'Explicit is better than implicit'
var3 = var.partition("IS")
print ("Original string:", var)
print ("Partition result:", var3)
Running this program produces the following output −
Original string: Explicit is better than implicit
Partition result: ('Explicit is ', 'better', ' than implicit')
Original string: Explicit is better than implicit
Segmented result: ('', 'Ex', 'plicit is better than implicit')
Original string: Explicit is better than implicit
Segmented result: ('Explicit is better than implicit', '', '')