Good use for itertools.dropwhile and itertools.takewhile
news at blinne.net
Tue Dec 4 21:33:52 CET 2012
Am 04.12.2012 20:37, schrieb Ian Kelly:
> >>> def split_product(p):
> ... w = p.split(" ")
> ... j = next(i for i,v in enumerate(w) if v.upper() != v)
> ... return " ".join(w[:j]), " ".join(w[j:])
> It still fails if the product description is empty.
That's true... let's see, next() takes a default value in case the
iterator is empty and then we could use some special value and test for
it. But i think it would be more elegant to just handle the excepten
>>> def split_product(p):
... w = p.split(" ")
... j = next(i for i,v in enumerate(w) if v.upper() != v)
... except StopIteration:
... return p, ''
... return " ".join(w[:j]), " ".join(w[j:])
> I'm not meaning to pick on you; some of the other solutions in this
> thread also fail in that case.
It's ok, opening the eye for edge cases is always a good idea :)
More information about the Python-list