Python String partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator, and the part after the separator. Here, the separator is a string that is given as the argument.
Example:
Python3
str = "I love Geeks for Lazyroar" print ( str .partition( "for" )) |
Output:
('I love Geeks ', 'for', ' Lazyroar')
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.
String partition() in Python Examples
Working of Python String partition() Method
In this example, we are demonstrating the use of the partition() method in Python with two separators attracts and is.
Python3
string = "light attracts bug" # 'attracts' separator is found print (string.partition( 'attracts' )) string = "gold is heavy" # 'is' as partition print (string.partition( 'is' )) |
Output:
('light ', 'attracts', ' bug') ('gold ', 'is', ' heavy')
The partition() Method only partitions on the first occurrence of the separator
In this example, we are showing that the Python String partition() Method only considers the first occurrence of the separator in the string. When the first occurrence of the separator will occur the string will be separated.
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')
Result of partition() Method when the separator is missing from the String
In this example, We are showing that the Python String partition() Method returns the original string as the first element of the tuple, and the remaining two elements are empty. As you can see ‘are’ is missing from the string ‘Lazyroar for Lazyroar’.
Python3
string = "Lazyroar for Lazyroar" print (string.partition( 'are' )) |
Output:
('Lazyroar for Lazyroar', '', '')
Used Partition() Method to get a domain name from the String
In this example, We are using the partition() to get the domain name of the URL String.
Python3
result = url.partition( "//" ) result = result[ 2 ].partition( "/" ) print (result[ 0 ]) |
Output:
www.example.com
Case sensitive Python
In this example, we are using two different case-sensitive separators fox and Fox, which return different tuples.
Python3
sentence = "The quick Brown fox jumps over the lazy Fox." result = sentence.partition( "fox" ) print (result) result = sentence.partition( "Fox" ) print (result) |
Output:
('The quick Brown ', 'fox', ' jumps over the lazy Fox.') ('The quick Brown fox jumps over the lazy ', 'Fox', '.')