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 = fr.read(N_bytes)		
bytesize = "\'" + str(blen) + "s" + "\'"  # '10s'			
print(bytesize)			
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.
Example:

 abc = "abc"
 print(repr(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:

 10s

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

Cheers,
Cameron Simpson cs@cskk.id.au