Splitting a string every 'n'

Andrew Koenig ark at research.att.com
Tue Jul 9 10:35:44 EDT 2002


Simon> What is the idiomatic way to split a string into a list
Simon> containing 'n' character substrings?  I normally do
Simon> something like:

Simon> while strng:
Simon>     substring = strng[:n]
Simon>     strng = strng[n:]
Simon>     <process substring>

How about this?

        for start in range(0, len(strng), n):
            substring = strng[start:start+n]
            <process substring>


-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list