string partition in python

String partition in python can be done easily by using a built-in method called partition(). This method is a string method.

There are two string partition methods.

  1. partition()
  2. rpartition()

1. partition()

The partition() method takes a separator as input and split the string at the first occurrence of the separator, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

Example

string partition method

The output of the above code is a 3 tuple value which is,

('python', 'code', 'rs')

We used the string ‘code‘ as a separator and hence the original string ‘pythoncoders‘ is split into three strings as one before the separator, one the separator itself, and one after the separator.

2. rpartition()

The rpartition() method is similar to the partition() method. But, if there are multiple occurrences of the string passed as the argument, the last occurrence will be used as the separator. String before the last occurrence will be separated as the first tuple value. Then, the string itself is separated next as the middle value and finally the string after the last occurrence is separated as the third value of the tuple.

Example

rpartition in python

The output of the above code is,

('The sun rises in ', 'the', ' East')

As we can see there are two ‘the‘ in our string and only the last occurrence is taken as the separator and the string before the first ‘the‘ is split as one result, the string itself as another result and finally the string after the ‘the‘ is split as the third value.

Conclusion

The partition methods are useful when we want to get the name and extension from a filename or in scenarios like that.

Happy coding !