Finding a Delimiter or Splitting Text

Finding a delimiter yields a position or a missing marker. Splitting uses rules that decide how many fields to produce.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a separator request
  2. Handle absent separators
  3. Trace an empty field and an absent separator
  4. Use a grammar when separators can be escaped

Trace a separator request

On "zone:east:daily", splitting once at a colon yields fields "zone" and "east:daily". Split every colon and there are three fields. When expecting exactly two fields, the input contract should explain whether additional colons belong to the second value.

Handle absent separators

Python's string find returns minus one for an absent substring. Using that value directly as an index reads from the end and can hide the failure. Distinguish a missing value marker from ordinary positions before using it to slice.[1]

Trace an empty field and an absent separator

On "track::4", splitting with the explicit delimiter ":" yields ["track", "", "4"] in Python. The middle empty field still has a position. Searching for the same delimiter returns index five for its first occurrence. On "track", find returns minus one. Slicing at that negative index by accident could drop the last character while suggesting the parse succeeded. Test both cases and treat absence explicitly. See negative sequence indices.

Use a grammar when separators can be escaped

A delimited row such as "a,b",20 contains a comma inside the first field. Splitting on every comma produces the wrong field count. A parser for the chosen format defines how quotes, escaped quotes and record endings behave together. For a simple key-value line where the value may contain the separator, splitting once can be enough. Test a separator in the value and an empty value under both designs. See whitespace in text records.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩