Parsing string into fixed-width pieces
Jeff Shannon
jeff at ccvcorp.com
Fri Mar 15 19:31:53 EST 2002
"Johnson, Brad" wrote:
> I'm new to Python and have been combing the documentation and the message
> archive here for information on splitting a string into fix-width pieces. I
> assume their is an easy way to do this, I just don't seem to be able to find
> it in the reference material. Any suggestions?
Something like this, perhaps?
>>> mystring = "123456789ABCDEF"
>>> mylist = [mystring[x:x+3] for x in range(0,len(mystring),3)]
>>> mylist
['123', '456', '789', 'ABC', 'DEF']
>>>
Note that it's not terribly common to want to split a string in fixed width
pieces. It's far more common that there's some sort of delimiting character
that you want to break on, and for those cases, there's the split method:
>>> mystring = "123,456,789,ABC,DEF"
>>> mylist = mystring.split(',')
>>> mylist
['123', '456', '789', 'ABC', 'DEF']
>>>
Hope that helps...
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list