Custom string joining

Martineau ggrp2.20.martineau at dfgh.net
Mon May 9 15:26:28 EDT 2011


On May 7, 5:31 am, Claudiu Popa <cp... at bitdefender.com> wrote:
> Hello Python-list,
>
> I  have  an object which defines some methods. I want to join a list or
> an iterable of those objects like this:
>
> new_string = "|".join(iterable_of_custom_objects)
>
> What   is   the   __magic__  function that needs to be implemented for
> this case to work?  I  though  that  __str__  is sufficient but it doesn't seems to
> work. Thanks in advance.
>
> PC

Instead of join() here's a function that does something similar to
what the string join() method does. The first argument can be a list
of any type of objects and the second separator argument can likewise
be any type. The result is list of the various objects. (The example
usage just uses a list of string objects  and separator to illustrate
what it does.)

def tween(seq, sep):
    return reduce(lambda r,v: r+[sep,v], seq[1:], seq[:1])

lst = ['a','b','c','d','e']

print tween(lst, '|')
print ''.join(tween(lst, '|'))

Output:

['a', '|', 'b', '|', 'c', '|', 'd', '|', 'e']
a|b|c|d|e


It could be made a little more memory efficient by applying the
itertools module's islice() generator to the first 'seq' argument
passed to reduce():

def tween(seq, sep):
    return reduce(lambda r,v: r+[sep,v], itertools.islice(seq,1,None),
seq[:1])


--
Martin



More information about the Python-list mailing list