Splitting a string every 'n'
Rich Harkins
rich at worldsinfinite.com
Tue Jul 9 14:21:54 EDT 2002
> On Tuesday 09 July 2002 08:50 am, 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>
>
Using python2:
[s[i:i+n] for i in range(0,len(s),n)]
where:
s - is the string to split
n - is the number of characters to break at
i - is some throwaway variable (previous value of i *not* protected)
Rich
More information about the Python-list
mailing list