Splitting a string every 'n'

Harvey Thomas hst at empolis.co.uk
Tue Jul 9 09:04:34 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>
> 
How about:

import re
rex = re.compile('....', re.DOTALL)

for substring in rex.findall(string):
	<process substring>

HTH

Harvey Thomas

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.





More information about the Python-list mailing list