views:

178

answers:

3

I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.

message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.')
result = split16(message, 16)
msg = ';'.join(encode(result.pop(0)) for i in result)

The encode function takes a 16 byte string and returns the result, however with the way it is written, it only encodes half of the elements in th list. ie, if there are 4 elements in the list, only 2 will be encoded. If there are 6, it only does 3.

If i try comprehension:

result = [encode(split16(message, 16) for message in list_of_messages)]
result = ''.join(result)

It results in the whole list being sent at once. What i need to do is send each element to the encode function separately, get the result then join them together.

Is there an easy way of achieving this ?

+1  A: 

Are you trying to do something like this?

';'.join(encode(i) for i in message.split('.'))

of course it could be just

';'.join(encode(i) for i in result)

if your split16 function complicated enough.

SilentGhost
A: 

I'm not quite clear what you are after, but

msg=";".join(map(encode,(message[i:i+16] for i in range(0,len(message),16))))
gnibbler
+1  A: 

I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren in the code you posted:

result = [encode(split16(message, 16) for message in list_of_messages]

Should that be:

result = [encode(split16(message, 16) for message in list_of_messages)]

or:

result = [encode(split16(message, 16)) for message in list_of_messages]

I think the second will do what you want.

This code:

msg = ';'.join(encode(result.pop(0)) for i in result)

is failing because at every step you are iterating through result, but shortening it at every step with pop. It should just be:

msg = ';'.join(encode(i) for i in result)
JAShapiro