Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
struct.decode() and '\0'
#1
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
Reply
#2
to strip trailing 0's from a string
typestr.strip('\x00')
if you need it removed from the bytes
typebytes.strip(b'\x00')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Struct Question, decimal 10, \n and \x0a. 3python 2 674 Aug-11-2023, 09:29 AM
Last Post: 3python
  Decode string ? JohnnyCoffee 1 825 Jan-11-2023, 12:29 AM
Last Post: bowlofred
  JS Buffer.from VS struct.pack DreamingInsanity 3 2,468 Apr-05-2021, 06:27 PM
Last Post: DreamingInsanity
  how to encode and decode same value absolut 2 2,356 Sep-08-2020, 09:46 AM
Last Post: TomToad
  struct.unpack failed Roro 2 3,364 Jun-13-2020, 05:28 PM
Last Post: DreamingInsanity
  Pack integer values as single bytes in a struct bhdschmidt 3 2,342 Jun-09-2020, 09:23 PM
Last Post: bhdschmidt
  Getting decode error. shankar 8 10,397 Sep-20-2019, 10:05 AM
Last Post: tinman
  How to remove empty struct from matlab file in python? python_newbie09 0 2,389 Jun-25-2019, 12:13 PM
Last Post: python_newbie09
  how to decode UTF-8 in python 3 oco 3 37,430 Jun-05-2018, 11:05 AM
Last Post: wavic
  Ask help for utf-8 decode/encode forfan 12 10,879 Feb-25-2017, 02:04 AM
Last Post: forfan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020