Splitting a string every 'n'

William Park opengeometry at NOSPAM.yahoo.ca
Tue Jul 9 11:48:17 EDT 2002


Simon.Foster at smiths-aerospace.com wrote:
> 
> 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>

No, you pretty much have to slice out the range you want, ie.
    substring = string[i:i+n]

-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin



More information about the Python-list mailing list