Stripping Text and Removing an Exact Prefix
Stripping removes characters from the ends according to a character set. Removing a prefix checks a single complete leading substring.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Try a revealing label
In Python, "abba".lstrip("ab") yields empty text because every leading character is either a or b. Removing the exact prefix "ab" yields "ba" instead. The distinction matters when parsing a textual representation.
Keep only the intended normalization
If a value needs one optional leading tag, remove that tag once and preserve the remaining characters. If input can have surrounding whitespace, check the format's whitespace rules separately. Canonicalizing labels can describe why any normalization is appropriate.[1]
Watch how a character set can remove too much
In Python, "bedsheet".lstrip("bed") removes leading characters from the set containing b, e and d until the first s, yielding "sheet". Applying the same operation to "beebread" also removes the next b, yielding "read". Removing a literal prefix "bed" would leave that second string unchanged. Test a near-prefix composed of the same characters. See prefix and suffix matches.
Do whitespace cleanup and structural parsing in order
Trimming a token before inspecting a literal prefix is appropriate only when the surrounding whitespace is outside the data grammar. For a space-sensitive identifier, it changes the spelling. If both operations are needed, test a prefixed value with multiple leading spaces and an unprefixed value starting with a prefix character. Preserve the raw input when a diagnostic must show exactly what was read. See whitespace in structured records.