A configuration line contains a key and a value separated by the first equals sign.
What You Need to Understand
split(separator) returns a list of fields, while partition(separator) returns exactly three parts: before the first separator, the separator itself, and the remainder. partition() therefore preserves whether and where the first separator was found.
When to Use It
A configuration line contains a key and a value separated by the first equals sign.
Step-by-Step Python Example
line = "token=a=b"
print(line.split("="))
print(line.split("=", 1))
print(line.partition("="))
How the Example Works
split("=") produces three pieces; split("=", 1) produces two. partition() returns ("token", "=", "a=b").
Example Output
['token', 'a', 'b']
['token', 'a=b']
('token', '=', 'a=b')
mode fast=quiet True
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
setting = "mode=fast=quiet"
key, separator, value = setting.partition("=")
print(key, value, bool(separator))
Important Behavior and Edge Cases
With no separator present, partition() returns the whole input followed by two empty strings. split() behaves differently, so choose the API for your parsing contract.
Try It Yourself
Parse "mode=fast=quiet" without losing the value after the first equals sign.
Common Beginner Mistakes
- With no separator present,
partition()returns the whole input followed by two empty strings.split()behaves differently, so choose the API for your parsing contract. - Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
split(separator)returns a list of fields, whilepartition(separator)returns exactly three parts: before the first separator, the separator itself, and the remainder.split("=")produces three pieces;split("=", 1)produces two.- With no separator present,
partition()returns the whole input followed by two empty strings.