Last Updated : 02 Jan, 2025
In Python, the String partition() method splits the string into three parts at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator itself, and the part after the separator.
Let's understand with the help of an example:
Python
s = "Geeks geeks"
res = s.partition("for")
print(res)
('Geeks geeks', '', '')Explanation:
'I love Geeks'
'for'
' Geeks'
Parameters:string.partition(separator)
(before_separator, separator, after_separator)
.(string, '', '')
.partition()
with a valid separator
This example demonstrates the behavior when the separator exists in the string:
Python
s = "Python is fun"
res = s.partition("is")
print(res)
('Python ', 'is', ' fun')Explanation:
"is"
.If the separator is absent, the partition()
method returns a specific result.
s = "Python is fun"
res = s.partition("Java")
print(res)
('Python is fun', '', '')Explanation:
"Java"
is not present in the string, the entire string is returned as the first element of the tuple.partition()
method only considers the first occurrence of the separator:
s = "Learn Python with GeeksforGeeks"
res = s.partition("Python")
print(res)
('Learn ', 'Python', ' with GeeksforGeeks')Explanation:
"Python"
.partition()
method. partition()
method works seamlessly with special characters:
s = "key:value"
res = s.partition(":")
print(res)
('key', ':', 'value')Explanation:
":"
.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4