The string partition() method in Python allows splitting the string at the specified location. It will return a new string with 3 parts: before the split position, at the split position, after the split position, and the positions are separated by ",". The specified position is treated as an argument.
Here at LinuxAPT, we shall look into how to use the partition() method in Python.
The partition() method is used to split a string into 3 parts according to the specified position:
It is given below:
string.partition(value)
String partition() Method Parameter Values:
value: the position you want to split
1. Take a look at the below function:
txt = "I wanna eat an apple"
x = txt.partition("eat")
print(x)
The Output will give:
('I wanna', 'eat', 'an apple')
2. The basic partition() method:
txt = "I wanna eat a banana"
x = txt.partition("eat")
print(x)
The Output will give:
('I wanna', 'eat', 'a banana')
3. The method did not find the specified location:
txt = "I wanna eat a banana"
x = txt.partition("cherry")
print(x)
The Output will give:
('I wanna eat a banana', ",")
It will print out the original string and 2 empty strings.
This article covers the usage of the partition() method in Python. In fact, Python partition() function is used to partition a string at the first occurrence of the given string and return a tuple that includes 3 parts – the part before the separator, the argument string (separator itself), and the part after the separator.
Python partition() function partition() Parameters
The partition() function accepts a single parameter: