Python Forum

Full Version: struct.decode() and '\0'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing some socket code and have to convert bytes to a str. The bytes contains a string that is padded with 0x00 to a fixed size. When I decode the bytes to get a str it leaves the trailing zeros in, so len(str) == len(bytes). Here's a short program that demonstrates this:
import struct
typebytes = ('LLfL'+'\0'*4).encode()
typestr = typebytes.decode()
print('typebytes', typebytes)
print('typestr ', typestr, '.', sep='')
Output:
typebytes b'LLfL\x00\x00\x00\x00' typestr LLfL .
Strangely when I run this code from IDLE I get "typestr LLfL." Must be a bug in the IDLE terminal. The code runs as described above when I run it from VS Code or from the shell (Windows 10 power shell or CMD shell both do the same). I am using Python 3.8.2 64 bit.

I know I can write code to remove the trailing zeros, but this has got to be so common that there's already a function that does it. Any suggestions greatly appreciated
to strip trailing 0's from a string
typestr.strip('\x00')
if you need it removed from the bytes
typebytes.strip(b'\x00')