[Python-Dev] join() et al.

M.-A. Lemburg mal@lemburg.com
Tue, 16 May 2000 19:15:05 +0200


Fredrik Lundh wrote:
> 
> >     Marc> join(seq,sep) := reduce(lambda x,y: x + sep + y, seq)
> >
> > Of course, while it will always yield what you ask for, it might not always
> > yield what you expect:
> >
> >     >>> seq = [1,2,3]
> >     >>> sep = 5
> >     >>> reduce(lambda x,y: x + sep + y, seq)
> >     16
> 
> not to mention:
> 
> >>> print join([], " ")
> TypeError: reduce of empty sequence with no initial value

Ok, here's a more readable and semantically useful definition:

def join(sequence,sep=''):

    # Special case: empty sequence
    if len(sequence) == 0:
        try:
            return 0*sep
        except TypeError:
            return sep[0:0]
        
    # Normal case
    x = None
    for y in sequence:
        if x is None:
            x = y
        elif sep:
            x = x + sep + y
        else:
            x = x + y
    return x

Examples:

>>> join((1,2,3))
6

>>> join(((1,2),(3,4)),('x',))
(1, 2, 'x', 3, 4)

>>> join(('a','b','c'), ' ')
'a b c'

>>> join(())
''

>>> join((),())
()

-- 
Marc-Andre Lemburg
______________________________________________________________________
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/