[Tutor] Splitting a string into n-sized bytes

Adam adam.jtm30 at gmail.com
Wed Mar 15 00:41:39 CET 2006


On 14/03/06, Steve Nelson <sanelson at gmail.com> wrote:
> 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.

How's this?:

>>> myString = "Sir, you are an egotistical rhetorician!!!"
>>> [myString[i:i+4] for i in range(0, len(myString), 4)]
['Sir,', ' you', ' are', ' an ', 'egot', 'isti', 'cal ', 'rhet',
'oric', 'ian!', '!!']

Hopefully that should point you in the right direction to do n-sized
words as well.


More information about the Tutor mailing list