python equiv of perl's split?

Bengt Richter bokr at oz.net
Mon Jan 13 12:31:28 EST 2003


On Mon, 13 Jan 2003 14:24:39 GMT, pete-temp-12-29-2002 at kazmier.com wrote:

>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?
>
Others have already mentioned that python's re has a split function,
but for a single character, I suspect the string method might be
faster. And since the it is not a variable pattern, you know what's
going to be returned, so why bother getting the ':' back?

You can always reconstitute the original with ':'join(pieces), e.g.

 >>> s = 'test:one:two:three'
 >>> sl = s.split(':')
 >>> sl
 ['test', 'one', 'two', 'three']
 >>> ':'.join(sl)
 'test:one:two:three'

Or mess with the pieces and join them differently

 >>> map(str.title, sl)
 ['Test', 'One', 'Two', 'Three']
 >>> ' :: '.join(map(str.title, sl))
 'Test :: One :: Two :: Three'

Just curious, what did you need the ':'s for?

Regards,
Bengt Richter




More information about the Python-list mailing list