If you are dealing with a zero-padded buffer then you can use rstrip to remove trailing \x00s

>>> text = 'Hello\x00\x00\x00\x00'
>>> text.rstrip('\x00')
'Hello'

It removes all \x00 characters at the end of the string but keeps any nulls in the middle. Not suitable for null-terminated strings that may contain random data after the terminator.

If you are dealing with a null-terminated string where the first zero indicates the end of string, but there might be other characters following it, you should use anregen's solution.

>>> text = 'Hello\x00\x24\x4e\x32'
>>> text.split('\x00', 1)[0]
'Hello'

It splits the text at the first zero and returns the slice. It works with strings having no null character too.

EDIT:
Explained rstrip in more detail and provided a correct use case.
Included alternative solution.

Answer from warownia1 on Stack Overflow
Discussions

python converting hexadecimal binary to string - Stack Overflow
I am using python3.5 and I wish to write output I get in hexadecimal bytes (b'\x00', b'\x01' etc) to python strings with \x00 -> 0 and \x01 -> 1 and I have this feeling it can be done easily... More on stackoverflow.com
🌐 stackoverflow.com
How to remove \\x00 from a string
Got an odd attachment name. The original data is which is quoted printable encoded ISO text, which is fine. At the end of the string, however, there is a \x00 character. Which makes code like dim theAttachment as Fol… More on forum.xojo.com
🌐 forum.xojo.com
0
0
February 7, 2019
How to delete "\x" from element in list
Looks like test.tab is actually a file containing binary data instead of ASCII text. How are you viewing it to get the first result you showed · Where does this file come from, and what do you expect that it should mean - what is the purpose of the contents · When you say that the file “is” ... More on discuss.python.org
🌐 discuss.python.org
0
0
April 21, 2024
Can someone explain how the datatype beginning with "\x" work?
That's not a "datatype", it's just a way of denoting unprintable characters in strings. "\x00" is the character with the hex code "00". "\xFF" is the character with the hex code "FF", or 255 in decimal. More on reddit.com
🌐 r/learnpython
5
6
June 29, 2017
🌐
Sololearn
sololearn.com › en › Discuss › 51585 › what-does-the-escape-sequence-x00-stand-for
What does the escape sequence '\x00 ' stand for | Sololearn: Learn to code for FREE!
September 7, 2016 - \x00 is thus a byte with all its bits at 0. (As Ryne pointed out, a null character translates to this.) Other examples: \xff is 11111111, \x7f is 01111111, \x80 is 10000000, \x2c is 00101010, etc.
🌐
Codeigo
codeigo.com › home › convert bytes to string
Convert Bytes to String - Codeigo
April 19, 2023 - This example shows what will happen when you change character encoding to a different one. As an example, we have a two-character string ‘PI’, which requires 2 bytes of memory to store one character.
🌐
Xojo Programming Forum
forum.xojo.com › general
How to remove \\x00 from a string - General - Xojo Programming Forum
February 7, 2019 - Got an odd attachment name. The original data is which is quoted printable encoded ISO text, which is fine. At the end of the string, however, there is a \x00 character. Which makes code like dim theAttachment as FolderItem = GetFolderItem(name) NameExtension = getExtensionFromFile(Name) fail with an NOE.
🌐
w3resource
w3resource.com › python › built-in-function › bytes.php
Python: bytes() function - w3resource
Python bytes() function: The bytes() function is used to get a new 'bytes' object.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
How to delete "\x" from element in list - Python Help - Discussions on Python.org
April 21, 2024 - hello, i have code a = open("test.tab") a = a.readlines() print(a) input() the file test.tab is 0001 0002 0001 0000 0000 0041 0001 0000 0001 0042 0001 0000 0002 0043 0000 0001 0000 0001 0000 0001 0001 0002 0000 …
🌐
Python Forum
python-forum.io › thread-25725.html
struct.decode() and '\0'
April 9, 2020 - 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...
🌐
Python
docs.python.org › 3.1 › library › struct.html
7.3. struct — Interpret bytes as packed binary data — Python v3.1.5 documentation
February 8, 2021 - >>> pack('llh0l', 1, 2, 3) b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00' This only works when native size and alignment are in effect; standard size and alignment does not enforce any alignment. ... Packed binary storage of homogeneous data. ... Packing and unpacking of XDR data. The struct module also defines the following type: ... Return a new Struct object which writes and reads binary data according to the format string format.
🌐
Quora
quora.com › In-python-3-why-when-I-write-code-b-x08-x00-x24-x32-and-when-I-display-code-I-get-b-x08-x00-2
In python 3, why when I write code = b'\x08\x00\x24\x32', and when I display code I get b'\x08\x00$2'? - Quora
Answer (1 of 3): TL;DR: It’s a side issue about how characters have been stored historically. You’re seeing weird throwback to that handling. Character \x24 (24 in hex) is ‘$‘ on the ASCII table. Character \x32 is ‘2’ on the table. In many older computer languages, a byte was used to store a cha...
Top answer
1 of 2
6

Something along the way is encoding your values as UTF-32. Simply decode them:

>>> b = u"c\x00\x00\x00o\x00\x00\x00n\x00\x00\x00t\x00\x00\x00e\x00\x00\x00\
... n\x00\x00\x00t\x00\x00\x00-\x00\x00\x00l\x00\x00\x00e\x00\x00\x00\
... n\x00\x00\x00g\x00\x00\x00t\x00\x00\x00h\x00\x00\x00"
>>> b.decode('utf-32')
u'content-length'
2 of 2
3

The root cause is that cStringIO.StringIO(unicode_object) produces a nonsense.

The current 2.X docs on docs.python.org say

Unlike the StringIO module, this module is not able to accept Unicode strings that cannot be encoded as plain ASCII strings.

This is unhelpful and incorrect; see below. The chm version of the docs supplied with the win32 installer for CPython 2.7.2 and 2.6.6 follow that with this sentence:

Calling StringIO() with a Unicode string parameter populates the object with the buffer representation of the Unicode string instead of encoding the string.

This is a correct description of the behaviour (see below). The behaviour is not brilliant. I can't imagine a good reason for that sentence being removed from the web docs.

Behaving badly:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
>>> import StringIO, cStringIO, sys
>>> StringIO.StringIO(u"fubar").getvalue()
u'fubar' <<=== unicode object
>>> cStringIO.StringIO(u"fubar").getvalue()
'f\x00u\x00b\x00a\x00r\x00' <<=== str object
cStringIO.StringIO(u"\u0405\u0406").getvalue()
'\x05\x04\x06\x04' <<=== "accepts"
>>> sys.maxunicode
65535 # your sender presumably emits 1114111 (wide unicode)
>>> sys.byteorder
'little'

So in general all one needs to do is know/guess the endianness and unicode-width of the sender's Python and decode the mess with UTF-(16|32)-(B|L)E.

In your case the sender is being rather Byzantine; for example u'content-length'.encode('utf-8') is the str object 'content-length' which bears a remarkable similarity to what you started with. Also foo.encode(utf8').decode('utf8') produces either foo or an exception.

🌐
Stack Overflow
stackoverflow.com › questions › 43287601 › how-to-convert-to-ascii-text-like-x00-in-python
how to convert to ascii text like \x00 in python - Stack Overflow
April 7, 2017 - Python: convert string to packed hex ( '01020304' -> '\x01\x02\x03\x04' ) 2 · Encode ASCII text · 0 · Printing Unicode Characters in Python (with '\x00') 1 · Write string of escaped byte characters, ie '\x00\x20\...', as if they were bytes · 0 · Converting \x00 with a space ·
🌐
Narkive
tutor.python.narkive.com › OPh8C373 › x00t-x00r-x00i-x00a-x00-ie-i-get-x00-breaking-up-every-character
[Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?
<snip> Something in the tool chain before it reached Python has saved it using a wide (four byte) encoding, most likely UTF-16 as that is widely used by Windows and Java. With the right settings, it could take as little as opening the file in Notepad, then clicking Save. UTF-16 is a two byte format. That's typically what Windows uses for Unicode. It's Unices that are more likely to use a four-byte format. Oops, you're right of course, two bytes, not four: py> u'M'.encode('utf-16BE') '\x00M' I was thinking of four hex digits: py> u'M'.encode('utf-16BE').encode('hex') '004d'
🌐
DataCamp
datacamp.com › tutorial › bytes-to-string-python
How to Convert Bytes to String in Python | DataCamp
June 12, 2024 - The bytes object displays this integer as \x00, the hexadecimal representation of 0. The final integer is 200, which is out of the ASCII range but within the range of integers that can be used in bytes. Python displays this integer as \xc8, which is 200 in hexadecimal. The bytes and strings data structures share common features.
🌐
Stack Overflow
stackoverflow.com › questions › 51907630 › python3-how-convert-string-to-x00
python - Python3: how convert string to "\x00...." - Stack Overflow
August 18, 2018 - How to convert j[1]['title'].encode('iso-8859-5') to string? str(j[1]['title'].encode('iso-8859-5')) wite to file as " b'\xc1\xd5\xe0\xd8\xef 20<br/>\xc1\xd5\xd7\xde\xdd 4' ", but need " \xc1\xd5\xe0\xd8\xef 20<br/>\xc1\xd5\xd7\xde\xdd 4 " ... You should stop playing with encodings where it's not really necessary. Everything works perfectly as it is: $ python >>> with open('part1.txt', 'w') as fout : ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert bytes to string
Python Convert Bytes to String - Spark By {Examples}
May 31, 2024 - # smile emoji - UTF-16 encoding byte_string = b'\xff\xfe(\x00?\x00?\x00)\x00' # Convert byte string to string string_utf16 = byte_string.decode('utf-16') print(string_utf16) # Output: # 😊 (smile emoji)