String building using join

Arnaud Delobelle arnodel at gmail.com
Tue Jan 4 15:36:56 EST 2011


gervaz <gervaz at gmail.com> writes:

> Hi all, I would like to ask you how I can use the more efficient join
> operation in a code like this:
>
>>>> class Test:
> ...     def __init__(self, v1, v2):
> ...         self.v1 = v1
> ...         self.v2 = v2
> ...

>>>> def prg(l):
> ...     txt = ""
> ...     for x in l:
> ...         if x.v1 is not None:
> ...             txt += x.v1 + "\n"
> ...         if x.v2 is not None:
> ...             txt += x.v2 + "\n"
> ...     return txt
> ...

You can change the prg() function above slightly to make it a generator
function:

def genprg(l):
    for x in l:
        if x.v1 is not None:
            yield x.v1
        if x.v2 is not None:
            yield x.v2

Then you can rewrite prg using join:

def prg(l):
    return '\n'.join(genprg(l))

This way you save yourself from creating a list.  I know this is not the
one liner that others have suggested but it shows a general way of
transforming a piece of code in order to make use of generator functions.

-- 
Arnaud



More information about the Python-list mailing list