String building using join

gervaz gervaz at gmail.com
Sun Jan 2 12:43:38 EST 2011


On 31 Dic 2010, 16:43, Emile van Sebille <em... at fenx.com> wrote:
> On 12/31/2010 7:22 AM gervaz said...
>
>
>
>
>
> > 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
> > ...
> >>>> t1 = Test("hello", None)
> >>>> t2 = Test(None, "ciao")
> >>>> t3 = Test("salut", "hallo")
> >>>> t = [t1, t2, t3]
>
> >>>> prg(t)
> > 'hello\nciao\nsalut\nhallo\n'
>
> > The idea would be create a new list with the values not None and then
> > use the join function... but I don't know if it is really worth it.
> > Any hint?
>
> >>>> def prg2(l):
>
>              return "\n".join([x for x in l if x])
>
> Emile
>
>
>
> > ...     e = []
> > ...     for x in l:
> > ...         if x.v1 is not None:
> > ...             e.append(x.v1)
> > ...         if x.v2 is not None:
> > ...             e.append(x.v2)
> > ...     return "\n".join(e)
> > ...
> >>>> prg2(t)
> > 'hello\nciao\nsalut\nhallo'
>
> > Thanks, Mattia- Nascondi testo citato
>
> - Mostra testo citato -- Nascondi testo citato
>
> - Mostra testo citato -

Sorry, but it does not work

>>> def prg3(l):
...     return "\n".join([x for x in l if x])
...
>>> prg3(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in prg3
TypeError: sequence item 0: expected str instance, Test found



More information about the Python-list mailing list