Python string Method - partition()
The partition()
method is a built-in string method in Python that returns a tuple containing three parts of the original string: the part before the first occurrence of a specified separator, the separator itself, and the part after the separator.
The syntax for using partition()
method is as follows:
string.partition(separator)
Here, string
is the original string, and separator
is the substring to search for in the string.
The method returns a tuple containing three strings:
- the part of the original string before the separator
- the separator itself
- the part of the original string after the separator
If the separator is not found in the original string, the method returns a tuple containing the original string and two empty strings.
Here's an example of using the partition()
method:
string = "Hello, World!" partition_tuple = string.partition(", ") print(partition_tuple)
Output:
('Hello', ', ', 'World!')
In the example above, the partition()
method was used to split the original string into three parts based on the separator ", "
. The resulting tuple contains the parts of the original string before and after the separator, as well as the separator itself.