The struct
module does only support fixed-length structures. For variable-length strings, your options are either:
-
Dynamically construct your format string (a
str
will have to be converted to abytes
before passing it topack()
):s = bytes(s, 'utf-8') # Or other appropriate encoding struct.pack("I%ds" % (len(s),), len(s), s)
-
Skip
struct
and just use normal string methods to add the string to yourpack()
-ed output:struct.pack("I", len(s)) + s
For unpacking, you just have to unpack a bit at a time:
(i,), data = struct.unpack("I", data[:4]), data[4:]
s, data = data[:i], data[i:]
If you’re doing a lot of this, you can always add a helper function which uses calcsize
to do the string slicing:
def unpack_helper(fmt, data):
size = struct.calcsize(fmt)
return struct.unpack(fmt, data[:size]), data[size:]