Parsing string into fixed-width pieces
Cliff Wells
logiplexsoftware at earthlink.net
Fri Mar 15 17:51:03 EST 2002
On Fri, 15 Mar 2002 14:44:45 -0600
Johnson, Brad wrote:
> Hello,
>
> 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?
Just use slices:
>>> s = "Hello, World"
>>> s[1]
'e'
>>> s[2:4]
'll'
>>> s[3:]
'lo, World'
>>>
To split it up into 4 pieces of length 3 (assuming your lengths are all the
same):
>>> l = 3
>>> for slice in range(0, len(s), l):
... print s[slice:slice + l]
...
Hel
lo,
Wo
rld
>>>
--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308 (800) 735-0555 x308
More information about the Python-list
mailing list