The partition() method in Python is a built-in string method that helps split a string into three parts based on a specified separator. The method searches for the separator within the string and divides it into three components: the part before the separator, the separator itself, and the part after the separator. The resulting parts are returned as a tuple.
Syntax:
string.partition(separator)
How to use the partition() method:
text = "Hello, World!"
result = text.partition(", ")
print(result)
Output:
('Hello', ', ', 'World!')
Example 1
Parsing email addresses.
email = "[email protected]"
username, separator, domain = email.partition("@")
print("Username:", username)
print("Separator:", separator)
print("Domain:", domain)
Output:
Username: example
Separator: @
Domain: example.com
Example 2
Splitting a URL into parts.
url = "https://www.example.com/path/to/page.html"
protocol, separator, remainder = url.partition("://")
domain, separator, path = remainder.partition("/")
print("Protocol:", protocol)
print("Separator:", separator)
print("Domain:", domain)
print("Separator:", separator)
print("Path:", path)
Output:
Protocol: https
Separator: ://
Domain: www.example.com
Separator: /
Path: path/to/page.html