Python String partition(), rpartition()

Filed Under: Python

Python String partition() function splits a string based on a separator into a tuple with three strings. The first string is the part before the separator, the second string is the separator and the third string is the part after the separator.

Python String partition()

This function syntax is:


If the separator string is not found, then the 3-tuple contains the string itself followed by two empty strings.

Let’s look at some examples of partition() function.

s = 'Hello World 2019'

parts_tuple = s.partition('World')

parts_tuple = s.partition('2018')


('Hello ', 'World', ' 2019')
('Hello World 2019', '', '')

python string partition

Python String rpartition()

Python String rpartition() splits the string at the last occurrence of the separator string. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

s = 'Hello World 2019'

parts_tuple = s.rpartition('World')

parts_tuple = s.rpartition('2018')


('Hello ', 'World', ' 2019')
('', '', 'Hello World 2019')

python string rpartition

Let’s look at an example where the difference between partition() and rpartition() function will be clear.

s = 'ABCBA'
parts_tuple = s.partition('B')

parts_tuple = s.rpartition('B')


('A', 'B', 'CBA')
('ABC', 'B', 'A')
You can checkout more Python examples from our GitHub Repository.

Official Documentation: partition()

Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages