python equiv of perl's split?

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Jan 13 09:58:17 EST 2003


pete-temp-12-29-2002 at kazmier.com wrote in 
news:m3k7h9p1p4.fsf at coco.kazmier.com:

> Just wondering what the 'best' way of emulating perl's split() method
> when used in the following manner:
> 
>      split /(:)/
> 
> Basically, split the string using a colon as the separator.  NOTE: the
> parens indicate that the split function should *include* the colons in
> the returned list.  Thus, given the string:
> 
>      test:one:two:three
> 
> The following array (list) is returned:
> 
>      test
>      :
>      one
>      :
>      two
>      :
>      three
> 
> What would be the easiest way to emulate this in Python?

Easiest is perhaps:

>>> re.findall(":|[^:]+", "test:one:two:three")
['test', ':', 'one', ':', 'two', ':', 'three']

But the best is probably to rewrite the code so you don't need the colons 
in the list.


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list