Python String partition[] method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, separator and the part after the separator. Here, the separator is a string that is given as the argument.
Python String partition[] Method Syntax:
Syntax: string.partition[separator]
Parameters:
- separator: a substring that separates the string
Return: Returns a tuple of 3 elements. The substring before the separator, the separator, the part after the separator.
Python String partition[] Method Example:
Python3
string
=
"geeks for geeks"
print
[string,
"after partition"
, string.partition[
"for"
]]
Output:
geeks for geeks after partition ['geeks ', 'for', ' geeks']
Example 1: Working of Python String partition[] Method
Python3
string
=
"light attracts bug"
print
[string.partition[
'attracts'
]]
string
=
"gold is heavy"
print
[string.partition[
'is'
]]
Output:
['light ', 'attracts', ' bug'] ['gold ', 'is', ' heavy']
Example 2: partition[] Method only partitions on first occurrence of separator
Python String partition[] Method only considers the first occurrence of the separator in the string.
Python3
string
=
"b follows a, c follows b"
print
[string.partition[
'follows'
]]
string
=
"I am happy, I am proud"
print
[string.partition[
'am'
]]
Output:
['b ', 'follows', ' a, c follows b'] ['I ', 'am', ' happy, I am proud']
Example 3: Result of partition[] Method when separator is missing from String
Python String partition[] Method returns the original string as the first element of the tuple, and the remaining two elements are empty.
Python3
string
=
"geeks for geeks"
print
[string.partition[
'are'
]]
Output:
['geeks for geeks', '', '']