String.join revisited (URGENT for 1.6)

Johannes Stezenbach yawyi at gmx.de
Tue May 30 16:51:44 EDT 2000


Terry Reedy <tjreedy at udel.edu> wrote:
>0. Tuples currently do not have methods, so a full (rather than half)
>implementation of the other choice is currently not possible!

There is no reason for tuples not to have methods.

>1. Any string can be used as a joiner, but not all tuple/lists can be
>joined (as join is currently implemented).  One input and the output are
>strings, and the other input is a sequence of strings.  Join is about
>strings, and not about general sequences (or even general tuples and
>lists).

It's a valid argument against join() generalization,
but irrelevant regarding sep.join(seq) vs. seq.join(sep).

>2. It is common to use one joinstring (such as ' ', ',' or ', ') to join
>mupliple stringseqs and rare to join one stringseq with multiple
>joinstrings.   (The same is true for realworl nails, staples, glue joining
>batches of wood, cardboard, fabric, paper, etc.)   It is at least as
>sensible to consider joining to be a method of the relatively stable (in
>any particular context) joiner as to think of it as a method of the more
>variable collection being joined.

This makes sense only if you think of separators as abstract objects.
But as they are usually short strings, I predict people will use a common
coding style like this:

  str1 = ", ".join(list1)
  str2 = ", ".join(list2)
  str3 = ", ".join(list3)

See? It's unreadable not only because it's the wrong way round, but also
because the "unframed" separator string looks funny (unusual/unfamiliar).

>3. Generalization seems more sensible this way.  For instance, suppose I
>want to be able to join any sequence and have non-string items converted to
>strings:
>
>import string;  join = string.join
>
>class joiner:
>  def __init__(s, sep):
>    # assert (type(sep) == type(''))
>    s.sep = sep
>  def join(s, seq):
>    # return s.sep.join(map(str, seq))
>    return join(map(str, seq), s.sep)  # don't have 1.6 yet
>
>comma = joiner(', ')
>comma.join((1,2,3))
># '1, 2, 3'
>comma.join('string')
># 's, t, r, i, n, g'

Despite all I said before, I like this one because it's both elegant
and confusing. Except that you commited a Python coding crime by
not naming self self.

Johannes




More information about the Python-list mailing list