[Tutor] String question.

Thu Apr 13 12:24:52 CEST 2006

```How's this?:
>>> s = """All,
...
... I have a problem/question I'd like to pose to you guys on how best to
... accomplish the following.  I have a string that will vary in size, what
... I would like to do is split into n size chunks.  I am also not sure how
... best to represent the chunks.  For example, say I have a len(s) = 200
... chars.  I'd like to get one chunk with 160 of those chars and the
... remaining 40 in a second.  Likewise, if I have a len(s) = 350, I'd like
... two chunks of 160 and a 3rd with the remainder.
...
... I don't know what it would best way to accomplish this.  I have the idea
... of converting the string to a list of chars loop through it until size
... is met, create a new string with s=s[:160], then start again, and so
... on.  Is this the only way to accomplish this? Or is there a more
... elegant/clever way?
...
... Thank you  :)"""
>>> l = []
>>> start = 0
>>> for i in range(160, len(s)+160, 160):
...     l.append(s[start:i])
...     start = i
...
>>>l
["All,\n\nI have a problem/question I'd like to pose to you guys on
how best to\naccomplish the following.  I have a string that will vary
in size, what\nI would like", " to do is split into n size chunks.  I
am also not sure how\nbest to represent the chunks.  For example, say
I have a len(s) = 200\nchars.  I'd like to get one ch", "unk with 160
of those chars and the\nremaining 40 in a second. Likewise, if I have
a len(s) = 350, I'd like\ntwo chunks of 160 and a 3rd with the
remainder.\n\nI d", "on't know what it would best way to accomplish
this.  I have the idea\nof converting the string to a list of chars
loop through it until size\nis met, create a ne", '', " to do is split
into n size chunks.  I am also not sure how\nbest to represent the
chunks.  For example, say I have a len(s) = 200\nchars.  I'd like to
get one ch", "unk with 160 of those chars and the\nremaining 40 in a
second.  Likewise, if I have a len(s) = 350, I'd like\ntwo chunks of
160 and a 3rd with the remainder.\n\nI d", "on't know what it would
best way to accomplish this.  I have the idea\nof converting the
string to a list of chars loop through it until size\nis met, create a
ne", 'w string with s=s[:160], then start again, and so\non.  Is this
the only way to accomplish this? Or is there a more\nelegant/clever
way?\n\nThank you  :)']
```