I feel stoopid ... this code is to verbose
David Eppstein
eppstein at ics.uci.edu
Fri Jun 14 14:30:00 EDT 2002
In article <3D0A1791.3060307 at mxm.dk>, Max M <maxm at mxm.dk> wrote:
> I just cannot seem to find the nice 3-liner I expected from the
> beginning. Has anybody got a better solution ? I thought somebody might
> find it a fun exercise. Well I have...
My attempt:
def stringSlicer(string, chunkSize = 3, sep='.'):
x = (len(string)-1)%chunkSize + 1
C = [string[max(0,chunkSize*(i-1)+x):chunkSize*i+x] \
for i in range((len(string)+chunkSize-1)//chunkSize)]
return sep.join(C)
I've split it into four lines for better readability -- you could get a
one-liner (without lambda or and-or tricks) by expanding the variables
(imagine the following all on one line):
def stringSlicer(string, chunkSize = 3):
return sep.join([string[max(0,chunkSize*(i-1) + \
(len(string)-1)%chunkSize+1) : \
chunkSize*i+(len(string)-1)%chunkSize+1] \
for i in range((len(string)+chunkSize-1)//chunkSize)])
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list