[Tutor] Concatenating numeric data in Python 3.3

eryksun eryksun at gmail.com
Wed Apr 24 21:09:27 CEST 2013


On Wed, Apr 24, 2013 at 2:23 PM, sparkle Plenty
<sparkle.plenty12481632 at gmail.com> wrote:
>  I will have an unknown number of instances, each of which consists of 3
> numeric values.  I tried packing each instance using struct.pack, then
> converting to  a tuple, then concatenating.  This ran, but introduced
> errors: in some instances, high order truncation of a leading zero in the
> first of the 3 values.  This throws off the position of all data that
> follows.  Error messages and error code are dependent on which technique is
> being tried.  The most recent ones are:
> TypeError: can't concat bytes to str
> TypeError: Can't convert 'tuple' object to str implicitly

If it's simply a matter of packing a number to a fixed number of
bytes, why not use the to_bytes method of a 3.x int?

    >>> b''.join(x.to_bytes(4, 'big') for x in [0x8badf00d,
0xd15ea5ed, 0xdeadd00d])
    b'\x8b\xad\xf0\r\xd1^\xa5\xed\xde\xad\xd0\r'


More information about the Tutor mailing list