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:
str.partition(sep)
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')
print(parts_tuple)
parts_tuple = s.partition('2018')
print(parts_tuple)
Output:
('Hello ', 'World', ' 2019')
('Hello World 2019', '', '')
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')
print(parts_tuple)
parts_tuple = s.rpartition('2018')
print(parts_tuple)
Output:
('Hello ', 'World', ' 2019')
('', '', 'Hello World 2019')
Let’s look at an example where the difference between partition() and rpartition() function will be clear.
s = 'ABCBA'
parts_tuple = s.partition('B')
print(parts_tuple)
parts_tuple = s.rpartition('B')
print(parts_tuple)
Output:
('A', 'B', 'CBA')
('ABC', 'B', 'A')
Official Documentation: partition()
Gracias por tus tutoriales, pareciera que hay un pequeño error.
s = ‘Hello World 2019’
parts_tuple = s.partition(‘World’)
print(parts_tuple)
parts_tuple = s.partition(‘2018’)
print(parts_tuple)
Si ingresas 2018, dejará 2 vacios hacia adelante (dado que no encuentra el valor), pero si ingresas 2019 solo 1