[Tutor] removing values using a loopy

Michael P. Reilly arcege@speakeasy.net
Wed, 25 Apr 2001 15:47:04 -0400 (EDT)


Sharriff Aina wrote
>=20
> Hi List!
>=20
> I retrieve strings from a database  using CGI in the format:
> [('Home, None, Kontakt, Termine, None, None')]
>=20
> as an example, this string varies according to the database entry made =
by
> the user
> I=B4m trying to generate HTML from these links by splitting the big str=
ing
> into singular values, my big problem is removing the  "None"s. I=B4ve t=
ried
> my best and rewrote the code at least 3 times, but my code fails and on=
ly
> works when the nones are at the end of the string, my code:

Three common idioms are to use the list methods and filtering and loops.

>>> noNone =3D string.split(s, ', ')
>>> while noNone.count('None') > 0:
...   noNone.remove('None')
...

and:
>>> noNone =3D filter(lambda s: s !=3D 'None', string.split(s, ', '))

and:
>>> noNone =3D []
>>> for x in string.split(s, ', '):
...   if x !=3D 'None':
...     noNone.append(x)
...

Of these, I think Tim and Guido were saying (some years ago) that the
most efficient would be the last one.  But don't let me put words into
their mouths. ;)

Also, notice that I use ', ' (with a space) in the separator, this
removes the leading whitespace which would likely be messing up your
comparisons in your other examples.

  -Arcege

PS: Someone pedantic enough can give some silly little list continuation
equivalent.  But the above are all version compatible, and since you
said you would like to have something soonest...

--=20
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |