Apr-09-2020, 03:11 PM
(This post was last modified: Apr-09-2020, 03:11 PM by deanhystad.)
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:
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
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
