• Uncategorized

About python : Print-without-b-prefix-for-bytes-in-Python-3

Question Detail

How do I print a bytes string without the b' prefix in Python 3?

>>> print(b'hello')

Question Answer

Use decode:

>>> print(b'hello'.decode())

If the bytes use an appropriate character encoding already; you could print them directly:



nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

If the data is in an UTF-8 compatible format, you can convert the bytes to a string.

>>> print(str(b"hello", "utf-8"))

Optionally, convert to hex first if the data is not UTF-8 compatible (e.g. data is raw bytes).

>>> from binascii import hexlify
>>> print(hexlify(b"\x13\x37"))
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
>>> from codecs import encode  # alternative
>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))

According to the source for bytes.__repr__, the b'' is baked into the method.

One workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))

>>> print(repr(x)[2:-1])

To show or print:


To encode or save:


I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:


It’s so simple…
(With that, you can encode the dictionary and list bytes, then you can stringify it using json.dump / json.dumps)

You just need use base64

import base64

data = b"Hello world!" # Bytes
data = base64.b64encode(data).decode() # Returns a base64 string, which can be decoded without error.

There are bytes that cannot be decoded by default(pictures are an example), so base64 will encode those bytes into bytes that can be decoded to string, to retrieve the bytes just use

data = base64.b64decode(data.encode())

Use decode() instead of encode() for converting bytes to a string.

>>> import curses
>>> print(curses.version.decode())

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.