Variable size for unpack function

Hello All,i am having an error of my python unpack script.
If i put directly ‘10s’ on the script it works fine.
But if i put in variable form like bytesize = “'” + str(blen) + “s” + “'”
I will be having an error:
Record 180 error, skipped! bad char in struct format.
Please someone suggest any solution. Thanks a lot
My code is below:

blen = len(Mybytesize)	# 10
N_bytes = blen			
bytes_read =		
bytesize = "\'" + str(blen) + "s" + "\'"  # '10s'			
handt, = struct.unpack(bytesize, bytes_read)			
handt = handt.decode("ascii")	

This puts a single quote at the start and end of the struct format
string. I suspect you’re misreading the docs - any quotes you’re forcing
into this are probably from writing a string as a Python expression.

 abc = "abc"

The string contains just the 3 letters, but the repr() surrounds that
in quotes as you would to express such a string in a programme.

I think the string you want is:


to collect 10 bytes of data.

Just do it like this:

 data_fmt = f'{blen}s'

to use as:

 handt_bs, = struct.unpack(data_fmt, bytes_read)
 handt = handt.decode("ascii")

Regarding variable names:

  • data_fmt: you’ve got a struct format string, this feels like a
    better name
  • handt_bs: a personal habit, I tend to name bytes values as
    foo_bs, particularly if I’ve got related but different values
    around like your handt, which is a str, not a bytes

Cameron Simpson