Splitting on '^' ?

Piet van Oostrum piet at cs.uu.nl
Fri Aug 14 17:48:43 EDT 2009


>>>>> kj <no.email at please.post> (k) wrote:

>k> Sometimes I want to split a string into lines, preserving the
>k> end-of-line markers.  In Perl this is really easy to do, by splitting
>k> on the beginning-of-line anchor:

>k>   @lines = split /^/, $string;

>k> But I can't figure out how to do the same thing with Python.  E.g.:

>>>>> import re
>>>>> re.split('^', 'spam\nham\neggs\n')
>k> ['spam\nham\neggs\n']
>>>>> re.split('(?m)^', 'spam\nham\neggs\n')
>k> ['spam\nham\neggs\n']
>>>>> bol_re = re.compile('^', re.M)
>>>>> bol_re.split('spam\nham\neggs\n')
>k> ['spam\nham\neggs\n']

>k> Am I doing something wrong?

It says that in the doc of 're':
Note that split will never split a string on an empty pattern match. For
example: 
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list