Library contents

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

  1. Start with "a=b"
  2. Do this Partition at the equals sign
  3. Result "a", "=", "b"
Partition keeps the matched separator between the two surrounding pieces.

Syntax

Python 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.

From the programfor field in ("token=a=b", "mode=", "broken"):
First output linetoken [a=b]
lesson.py
for field in ("token=a=b", "mode=", "broken"):
    key, separator, value = field.partition("=")
    if separator:
        print(f"{key} [{value}]")
    else:
        print("missing separator")
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result3

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?

Given3 · 0 · 8 · 3
Worked result3