Partition method in python [partition()]

Python’s data types are a treasure trove of built-in goodies. One of those goodies is the partition method — an alternative to the popular split() method.

The partition() method is used to break up a string based on a specified substring and all parts of the original string in a three-value tuple.

Implementing the partition() Method

Since partition() is a method, it must be called from a string object. This means that it cannot be called as a standalone function.

myString.partition() # valid
"Python".partition() # valid
partition(myString) # invalid

The method accepts a single required argument — a string that will be searched for.

myString.partition("search string")

The method will return a tuple — immutable, ordered data type — with three values. Assuming the substring is found, the three values will be (1) text before, (2) substring, and (3) text after.

What happens if the substring is not found? The method will still return a three-value tuple, but index 2 and 3 will be empty strings.

How Will You Use This?

Unless you’ve come to this article with a problem in hand, it may be difficult to see how you would use this method. To help, let’s compare and contrast partition() to the more commonly used split() method.

The two methods break apart a string; however, these qualities make partition() unique:

  • Only splits the string once.
  • Keeps track of the delimiter.
  • Always returns the same data structure.

So, if you need to split the string only at the first occurrence, use the delimiter later on, or rely on a guaranteed data structure, then the partition() method is most likely the best tool for the job.

Thanks for reading, please share your comments and experiences below in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *