Splitting a string into groups of three characters

John Machin sjmachin at lexicon.net
Mon Aug 8 00:08:37 EDT 2005


gene tani wrote:
> Um, you shd 1st search  cookbook, or Vaults Parnassu, dmoz python
> section,  pypackage:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689

which includes e.g.

def each_slice_lol(listin,n):
"""non-overlapp'g slices, return (list of lists) """
     len_listin=len(listin)
     return [listin[i:min(len_listin, i+n)] for i in range(0,len_listin,n)]

and the listin[i:min(len_listin, i+n)] is grossly wasteful; it does 
EXACTLY the same as listin[i:i+n] for the values of i and n that make sense.

 From the Python reference manual:
"""The semantics for a simple slicing are as follows. The primary must 
evaluate to a sequence object. The lower and upper bound expressions, if 
present, must evaluate to plain integers; defaults are zero and the 
sys.maxint, respectively. If either bound is negative, the sequence's 
length is added to it. The slicing now selects all items with index k 
such that i <= k < j where i and j are the specified lower and upper 
bounds. This may be an empty sequence. It is not an error if i or j lie 
outside the range of valid indexes (such items don't exist so they 
aren't selected).
"""



More information about the Python-list mailing list