Library contents

Python Length check before slicing

A Python slice can return a shorter prefix if a label ends early. Check the minimum length before routing the package.

A simple example

Length check before slicing

  1. Start with Text "A"
  2. Do this Request a two-character prefix
  3. Result Too short
Only one character is available. Check the length before extracting two.

Syntax

Python syntax
len(code) >= 3
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Read the depot prefix on a damaged label

A parcel scanner expects a three-character depot prefix. A torn label supplies only two characters, so the parcel should go to manual sorting before the software extracts the prefix.

From the programcode = "NE"
ResultSend to manual sorting
lesson.py
code = "NE"
print(code[:3] if len(code) >= 3 else "Send to manual sorting")
Output
Send to manual sorting

Two letters cannot identify the three-letter depot. The code routes the parcel to a clerk.

Advertisements

Read a complete lab identifier

A student scans a box showing the code BIO7. Extract the three-character prefix. A short scan must be repeated before the record is filed.

GivenBIO7 · take 3
Worked resultPrefix available

Identify an incomplete scan

A label is folded under the scanner and only two letters reach the form. Extract the three-character prefix. A short scan must be repeated before the record is filed.

GivenAR · take 3
Worked resultRescan

What to watch for

String slicing counts Unicode code points. The depot alphabet here contains only ASCII letters.

Documentation for Length check before slicing