Python str.partition
str.partition splits on the first literal separator and returns a three-item tuple containing the prefix, separator, and suffix.
A simple example
str.partition
- Start with "a=b"
- Do this Partition at the equals sign
- Result "a", "=", "b"
Syntax
key, separator, value = text.partition("=")
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Preserve empty values in key-value text
An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.
for field in ("token=a=b", "mode=", "broken"):
key, separator, value = field.partition("=")
if separator:
print(f"{key} [{value}]")
else:
print("missing separator")
token [a=b] mode [] missing separator
When the delimiter is absent, the middle item is empty. That identifies a malformed record even when an empty value would otherwise be valid.
Python documentation for str.partition
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The desk separates zero-quantity records for review. How many positive entries remain in the other group?
Review print quantities
A print room records four job quantities, including a cancelled job. The desk separates zero-quantity records for review. How many positive entries remain in the other group?