Parsing/Splitting Line

Noah Rawlins noah.rawlins at comcast.net
Tue Nov 21 19:48:23 EST 2006


acatejr at gmail.com wrote:
> I have a text file and each line is a list of values.  The values are
> not delimited, but every four characters is a value.  How do I get
> python to split this kind of data?  Thanks.
> 

I'm a nut for regular expressions and obfuscation...

import re
def splitline(line, size=4):
     return re.findall(r'.{%d}' % size, line)

 >>> splitline("helloiamsuperman")
['hell', 'oiam', 'supe', 'rman']


or if you care about remainders...

import re
def splitline(line, size=4):
     return re.findall(r'.{%d}|.+$' % size, line)

 >>> splitline("helloiamsupermansd")
['hell', 'oiam', 'supe', 'rman', 'sd']


noah



More information about the Python-list mailing list