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. Now we will teach you to use the partition() method in Python.
txt = "I wanna eat an apple" x = txt.partition("eat") print(x)
(‘I wanna ‘, ‘eat’, ‘ an apple’)
The partition() method is used to split a string into 3 parts according to the specified position.
Part 1: before the split position
Part 2: at the split position
Part 3: after the split position
value: the position you want to split
Example 1: The basic partition() method
txt = "I wanna eat a banana" x = txt.partition("eat") print(x)
(‘I wanna ‘, ‘eat’, ‘ a banana’)
Example 2: The method did not find the specified location
txt = "I wanna eat a banana" x = txt.partition("cherry") print(x)
(‘I wanna eat a banana’, ”, ”)
It will print out the original string and 2 empty strings.
We have already taught you the usage of the partition() method in Python.
Thank you for referring!
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.