Packing data

Fredrik Lundh fredrik at pythonware.com
Thu May 2 02:15:47 EDT 2002


bvdpoel at uniserve.com wrote:
> I figured that struct.pack('b', var) might work ... but var can't be a
> list and the fmt string has to be the right size. So, I can do something
> like:
>
> struct.pack('bbb', v1, v2, v3)

>>> struct.pack("b"*len(x), *x)
'\x01\x02\x03\x04\x05'

but if you're working with arrays, it probably makes
more sense to use the built-in array module:

>>> import array
>>> array.array("B", x).tostring()
'\x01\x02\x03\x04\x05'

or you could use map/join:

>>> import string
>>> string.join(map(chr, x), "")

also see:

    http://www.python.org/doc/essays/list2str.html

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->






More information about the Python-list mailing list