Scripting

Python String partition() Method

Python String partition() Method

Introduction

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.

Example

txt = "I wanna eat an apple"

x = txt.partition("eat")

print(x)

Output:

(‘I wanna ‘, ‘eat’, ‘ an apple’)

Definition

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

The syntax

string.partition(value)

Parameter Values:

value: the position you want to split

More examples

Example 1: The basic partition() method

txt = "I wanna eat a banana"

x = txt.partition("eat")

print(x)

Output:

(‘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)

Output:

(‘I wanna eat a banana’, ”, ”)

It will print out the original string and 2 empty strings.

Conclusion

We have already taught you the usage of the partition() method in Python.

Thank you for referring!

Similar Posts