Martin Walsh wrote: > Ricardo Aráoz wrote: >> Emil wrote: >>> hey >>> >>> I want to be capable of converting a string into a list where all the >>> items, in the list, have a fixed length not equal to 1 e.g i have k = >>> 'abcdefgh' and I want the fixed length for all the the items to be 2 then >>> the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this? >>> >>> >> Also : [''.join(i) for i in zip(k[::2], k[1::2])] > > Cool use of 'zip' and extended slicing! >
Thx > Just thought I would add that 'zip' truncates after the shortest > sequence, which would cause data loss for strings of odd length -- of > course, the OP may not consider this a problem. > > In [1]: k = 'abcdefghi' # <- note the 'i' > > In [2]: len(k) > Out[2]: 9 > > In [3]: [''.join(i) for i in zip(k[::2], k[1::2])] > Out[3]: ['ab', 'cd', 'ef', 'gh'] # <- 'i' is gone > Could only think of : [''.join(i) for i in zip(k[::2], k[1::2])] + list(k)[-(len(k)%2):0:-len(k)] But maybe it is too complicated. There should be a simpler way. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor