Python String partition() Method
The partition()
method splits the string at the first occurrence of the specified string separator sep
argument and returns a tuple containing three elements, the part before the separator, the separator itself, and the part after the separator.
If the matching separator is not found in the string then returns a tuple containing three elements, the string itself as a first element and two empty string elements.
Syntax:
str.partition(sep)
Parameters:
sep: (Required) A string separator.
Return Value:
- Returns tuple that contains three elements
- The part before the separator as a first element, the separator itself as a second element, and the part after the separator as a third element if the specified separator is found.
- If the specified separator is not found, then returns the string itself as a first element and two empty string elements.
The following example demonstrates the partition()
method:
mystr = 'Hello World'
print(mystr.partition(' '))
mystr = 'How are you?'
print(mystr.partition('are'))
('hello', ' ', 'world')
('How ', 'are', ' you?')
The partition()
method search is case-sensitive. It treats 'Tutorials' and 'tutorials' as two separate words, as shown below.
mystr = 'TutorialsTeacher is the best tutorials website.'
print(mystr.partition('tutorials'))
print(mystr.partition('Tutorials'))
('TutorialsTeacher is the best ', 'tutorials', ' website')
('', 'Tutorials', 'Teacher is the best tutorials website')
In the above example, 'tutorials' and 'Tutorials' are treated as two different separators and so returns two different tuples. Note that if a separator string is found at the start of a string, then the first element of a returning tuple will be empty, as in the case of 'Tutorials' separator in the above example.
If the separator is not present in the string, then the tuple contains the original string and two empty strings, as shown below.
If the separator is an empty string, then the partition()
method will throw ValueError
, as shown below.
mystr = 'Hello World'
print(mystr.partition('s'))
mystr = 'Hello World'
print(mystr.partition(''))
('Hello World', '', '')
ValueError: empty separator
The separator passed can be numbers as well as symbols.
mystr = '#1 Harbor Side'
print(mystr.partition('1'))
('#', '1', ' Harbor Side')
The partition()
method will only split the string at the first occurrence of the separator.
mystr="TutorialsTeacher"
print(mystr.partition("T")
('', 'T', 'utorialsTeacher')
The partition()
method performs case-sensitive search.
mystr="TutorialsTeacher"
print(mystr.partition("t")
('Tu', 't', 'orialsTeacher')