Whitespace and Empty Fields in Text Records
Separators, padding, and meaningful space can coexist in one file. A parser needs an explicit rule for which to preserve.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two splits
Python "two words".split() produces two fields by treating the whitespace run as one boundary. Splitting on an explicit single space yields an empty field between the two words. Choosing the operation changes the representation of the input.
Use the format specification
Fixed-width data can use spaces to align columns. An unrestricted strip may move columns or remove meaningful padding. Inspect raw values with text representations, then preserve the original offsets until the field boundaries are applied.[1]
Work out which whitespace belongs to the format
Imagine a fixed-width field consisting of " AB" followed by four digits. Removing leading whitespace shifts every later position by one. In a separate file of human-entered comma-separated lengths, surrounding spaces in numeric fields might be intentionally ignored. Separate the record boundary, field boundary and field conversion rules so whitespace is handled at the correct level. Test a value with spaces inside its field as well as around it. See reading a text file explicitly.
Inspect the last line even if it has no line ending
When reading a record per line, remove a newline according to the file's convention and preserve other characters until validation. Stripping all whitespace can also turn a record containing only tabs into an empty string, losing its diagnostic detail. A test containing empty lines, whitespace-only lines and a final unterminated line identifies three cases separately. See iterating over lines for how those inputs reach the parser.