Here is my code (py3.1):
def get_string(self,chars):
return struct.unpack("{}s".format(chars),self.get_bin(chars))
b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?
It helps when asking questions if you make sure that the code is actually what you did run. What you show would have given an error. Also ensure that the code snippet includes all information so that people don't need to guess.
>>> chars = "MESH" # guess
>>> binchars = b"MESH" # guess
>>> struct_fmt = "{}s".format(chars) # what you showed
>>> struct_fmt
'MESHs' ############### won't work
>>> import struct
>>> struct.unpack(struct_fmt, binchars)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: bad char in struct format ############ didn't work
>>> struct_fmt2 = "{}s".format(len(chars)) # what you probably did use
>>> struct_fmt2
'4s' #### looks much better
>>> struct.unpack(struct_fmt2, binchars)
(b'MESH',) ### did work
>>>
As the manual says, "For unpacking, the resulting bytes object ..."
chars is the number of chars in the desired string, not the string itself like you "guessed". (It does look like you answered the question though. So I forgive you.){}) gave no clue at all. You didn't show the WHOLE code (self.get_bin(chars) ???) so that somebody could reproduce what you were doing. In fact, all you needed to show to demonstrate what you meant was struct.unpack("4s", b"MESH")This works:
return struct.unpack("{}s".format(chars),self.get_bin(chars))[0].decode('ASCII')
But does not explain why unpack() neglects to do this itself. I'll leave the question open until that's answered.
Edit: Jason's improvement:
return self.get_bin(chars).decode('ASCII')
Makes a mockery of struct really...
struct to decode a string?? And even if struct would be expected to do this, how would struct.unpack be able to automatically infer whether the string is ASCII or UTF8 or some other type of unicode?10s > char[10] and 10w > wchar_t[10]? I'm assuming there is actually a way, as it does claim to do string.struct ... struct is for structures that might require a format like "<4s2H2Bd"
bytesinto into astr, you are doing it wrong(tm).structis for dealing with tightly-laid-out binary(!) data.