python equiv of perl's split?

Mike C. Fletcher mcfletch at rogers.com
Mon Jan 13 16:09:25 CET 2003


Here's a straightforward function to do the splitting as described if 
you wanted to code it yourself (you probably don't, but in case you ever 
wanted to (see below))...

import re

def split( pattern, string ):
    o = re.compile( pattern )
    result = []
    curResult = o.search( string )
    while curResult and string:
        start, stop = curResult.span(0)
        result.append(string[:start])
        result.append(string[start:stop])
        string = string[stop:]
        curResult = o.search( string )
    result.append( string )
    return result

s = "test:one:two:three"
print split( ':', s )

Here's the proper way to do it:

    re.split( '(:)', s )

(In general Python's re module follows Perl's re implementation, look 
there for perlisms :) ).  I would have thought this would work to, but 
it doesn't :( , re's suck :) .

    re.split( '(?=:)|(?<=:)', s )

Oh well, hope this helps,
Mike


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?
>
>Thanks,
>Pete
>
>  
>

-- 
_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list