Splitting a string every 'n'

Simon.Foster at smiths-aerospace.com Simon.Foster at smiths-aerospace.com
Tue Jul 9 08:50:19 EDT 2002


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>





More information about the Python-list mailing list