Good use for itertools.dropwhile and itertools.takewhile
MRAB
python at mrabarnett.plus.com
Tue Dec 4 15:17:19 EST 2012
On 2012-12-04 19:37, Ian Kelly wrote:
> On Tue, Dec 4, 2012 at 11:48 AM, Alexander Blinne <news at blinne.net
> <mailto:news at blinne.net>> wrote:
>
> Am 04.12.2012 19:28, schrieb DJC:
> >>>> (i for i,v in enumerate(w) if v.upper() != v).next()
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in <module>
> > AttributeError: 'generator' object has no attribute 'next'
>
> Yeah, i saw this problem right after i sent the posting. It now is
> supposed to read like this
>
> >>> 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.
>
> >>> split_product("CAPSICUM RED")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 3, in split_product
> StopIteration
>
> I'm not meaning to pick on you; some of the other solutions in this
> thread also fail in that case.
>
> >>> re.findall(r"(?m)^([A-Z\s]+) (.+)$", "CAPSICUM RED")
> [('CAPSICUM', 'RED')]
>
That's easily fixed:
>>> re.findall(r"(?m)^([A-Z\s]+)(?: (.*))?$", "CAPSICUM RED")
[('CAPSICUM RED', '')]
> >>> prod_desc("CAPSICUM RED") # the second version from Neil's post
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 14, in prod_desc
> IndexError: string index out of range
>
More information about the Python-list
mailing list