Parsing Text and Formatting Values
Parsing recovers a value from a representation. Formatting creates text for a particular reader or external interface.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Map many inputs to one value
Python can parse "007" and "7" as the integer seven. The original spelling is then unavailable from the number alone. Keep the text if padding represents a badge ID or another domain meaning.
Choose the requested output
Given the number seven, a formatter can produce "7" for a human and "007" for a fixed-width field. Numeric sorting uses the numeric values and display applies afterward. Check lexicographic ordering when a table orders "10" ahead of "2", since it may be comparing formatted strings.[1][2]
Make the round trip fit the domain
Parsing the text "02.50" into a measurement can produce the numeric value two and a half. Formatting that value as "2.50" preserves the number while changing the spelling. A report with a fixed-width field may instead require both leading and trailing digits. Decide what the consumer expects to recover after reading the export again. See lossless record round trips for how this difference affects the test.
Keep conversions at predictable edges
A table sorted by measurement magnitude should keep numeric measurements while arranging the rows. If it formats them first, a later text sort can put "10.0" before "2.5". Likewise, a parser should validate bounds once the number has a numeric meaning. A display function can round to its chosen precision without modifying the original stored value.
For a small independent test, choose two accepted spellings of a quantity, one invalid spelling, and two values that appear identical after rounding. Verify each conversion result and check the display separately. Then try an identifier with leading zeros. This is a valid alternative design for an input field, and it is tested by preserving the text rather than parsing it as a count. Typed input records keeps that choice explicit.