Mikael S. Mikael S. - 10 months ago 60
Python Question

How to make a fixed-size byte variable in Python

Let's say, I have a string (unicode if it matters) variable which is less than 100 bytes. I want to create another variable with exactly 100 byte in size which includes this string and is padded with zero or whatever. How would I do it in Python 3?

Answer Source

For assembling packets to go over the network, or for assembling byte-perfect binary files, I suggest using the struct module.

Just for the string, you might not need struct, but as soon as you start also packing binary values, struct will make your life much easier.

Depending on your needs, you might be better off with an off-the-shelf network serialization library, such as Protocol Buffers; or you might even just use JSON for the wire format.