ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-tutor
python-tutor
[Tutor] Splitting a string into n-sized bytes
by Steve Nelson other posts by this author
Mar 14 2006 3:11PM messages near this date
Re: [Tutor] Tix: binding | Re: [Tutor] Splitting a string into n-sized bytes
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.
_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Steve Nelson
Adam
Steve Nelson
Kent Johnson
Smith

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved