Joining a Sequence of Text Fragments

A separator-based join places a delimiter between neighboring fragments and gives an exact layout for empty and singleton inputs.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace the delimiter positions
  2. Check the outer syntax
  3. Choose the separator from the output format
  4. Separate quoting from joining

Trace the delimiter positions

Joining A, empty text, and B with a comma produces "A,,B". The two delimiters preserve the middle empty field. This follows the count of gaps from adjacent pair iteration.

Check the outer syntax

Joining a single field yields that field with no separator. If a record format needs a line terminator, supply it in the writer. When fields can contain the separator itself, use proper format-specific quoting before writing or parsing fields.[1]

Choose the separator from the output format

Joining ["", "amber", "blue"] with a pipe produces "|amber|blue". The empty first element is meaningful if readers expect three fields. Join inserts separators between adjacent fragments, so zero fragments produce an empty string and one fragment receives no added separator. A trailing newline for a text file is a separate decision about record termination. Test zero, one and three pieces. See splitting strings for cases in which the inverse is ambiguous.

Separate quoting from joining

If a field already contains a pipe, the serialized text becomes ambiguous unless the format has quoting or escaping rules. Convert records using the target format's serializer first. Repeatedly appending to an immutable string can also entail copying preceding text depending on language and implementation. When fragments already exist, joining them expresses a single assembly step. When output is huge, write progressively and verify record boundaries. See formatting versus parsing.

References

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