Splitting a string every 'n'
Terry Reedy
tjreedy at udel.edu
Tue Jul 9 10:15:49 EDT 2002
<Simon.Foster at smiths-aerospace.com> wrote in message
news:mailman.1026219434.22644.python-list at python.org...
>
> What is the idiomatic way to split a string into a list
> containing 'n' character substrings? I normally do
> something like:
>
> while strng:
> substring = strng[:n]
> strng = strng[n:]
> <process substring>
You are asking two different questions in you text and code:
1. How generate explicit list of successie length n substrings
(slices)?
2. How process successie length n substrings (slices), (which can then
be tossed)?
Second is easier than first: both require attention to possibility of
remainder of length less than n.
...
> Any better ideas, short of manually indexing through?
What, pray tell, is wrong with doing the simple obvious thing that you
can program correctly in a minute or two?
> Is there something like:
>
> for substring in strng.nsplit():
> <process substring>
Note that this says that (2) rather that (1) above is your question.
For 2.2+, write a generator that manually indexes thru sequence,
returning successive slices. A second param could determine whether a
short tail is returned or suppressed.
Terry J. Reedy
More information about the Python-list
mailing list