Splitting a string every 'n'

Simon Foster simon at uggs.demon.co.uk
Wed Jul 10 16:32:44 EDT 2002


On 9 Jul 2002 12:59:48 -0700, b_mcerlean at yahoo.com (Brian McErlean)
wrote:

>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>
>> 
>> But the performance of this is hopeless for very long strings!
>> Presumable because there's too much list reallocation?  Can't Python
>> just optimise this by shuffling the start of the list forward?
>> 
>> Any better ideas, short of manually indexing through?  Is there
>> something like:
>> 
>> for substring in strng.nsplit():
>>     <process substring>
>
>I have a handy class I use for things like this:
>
>
>class Group:
>  def __init__(self, l, size):
>    self.size=size
>    self.l = l
>
>  def __getitem__(self, group):
>    idx = group * self.size
>    if idx > len(self.l): 
>      raise IndexError("Out of range")
>    return self.l[idx:idx+self.size]
>
>I use it mainly for grouping things like:
>for x,y in Group([1,2,3,4,5,6,7,8,...],2): 
>  process_coords(x,y)
>but its also applicable to your problem, and works neatly with
>strings.
>
>try:
>
>for substring in Group(string, n):
>  <process substring>
>
>Don't you just love python's polymorphism!
>
>You don't state what you want to do if the string isn't a multiple of
>N characters.  This version includes the shorter string at the end.
>
>Brian.

That's what I wanted!
--
Simon Foster
Cheltenham
England



More information about the Python-list mailing list