This guide explains str.partition Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str.partition(separator) splits a string once at the first occurrence of a nonempty separator. It always returns three parts: before, separator, and after. If the separator is absent, the latter two parts are empty.
When You Would Use This
Split a key-value record while preserving any extra equals signs in the value.
Step-by-Step Example
record_text = "token=abc=123"
key_text, separator, value_text = record_text.partition("=")
print(key_text)
print(separator)
print(value_text)
How the Example Works
The key is token, the separator is =, and the value is abc=123. Unlike unrestricted .split("="), a single partition does not lose the structure of the remaining text.
Example Output
token
=
abc=123
Try It Yourself
Try a record without = and explain all three returned parts.
Common Beginner Mistakes
- Expecting only two return values.
- Using an empty separator, which raises
ValueError. - Confusing
.partition()with a full parser for escaped or quoted formats.
Key Takeaways
str.partition(separator)splits a string once at the first occurrence of a nonempty separator.- The key is
token, the separator is=, and the value isabc=123. - Avoid this mistake: Expecting only two return values.