[Tutor] Splitting a string into n-sized bytes

Steve Nelson sanelson at gmail.com
Wed Mar 15 00:11:10 CET 2006


Hello all,

Further to my previous puzzling, I've been working out the best way to
chop a string up into n-sized words:

I'm aware that I can use a slice of the string, with, eg, myWord[0:4].

I am also aware that I can do blob = myWord.pop(0) to take (and
remove) the first character.  I can botch these together, eg
myFourLetterWord =
myWord.pop(0)+myWord.pop(0)+myWord.pop(0)+myWord.pop(0) but that is
really horrid.

I then tried doing something suitably silly, as follows:

1) Find the length of string.
2) Create a list using range(0, length, 4)
3) We now have the end points for each 'word', eg 4, 8, 12.
4) Now create a list of tuples that represent the slices we need, ie
(0,4), (5,8) etc
5) Iterate over this list, grabbing the slices as depicted in the tuples.
6) Use these tuples to grab slices.

The code looked like this:
#!/usr/bin/env python
myString = "Sir, you are an egotistical rhetorician!!!"
length=len(myString)
extra=length%4
if extra > 0:
  myString = myString+("#"*extra)+"#"
r = range(0, len(myString), 4)
wordRange=[]
for i in r:
  if i>1:
    wordRange.append((int(i-4),i))
for t in wordRange:
  print myString[t[0]:t[1]]

Surely there's an easier way?

S.


More information about the Tutor mailing list