How do I print a bytes string without the b' prefix in Python 3?
>>> print(b'hello') b'hello' Use decode:
>>> print(b'hello'.decode()) hello encoding parameter when not set is indeed 'utf-8': docs.python.org/3/library/stdtypes.html#bytes.decodeAccording 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)) b'\x01\x02\x03\x04' >>> print(repr(x)[2:-1]) \x01\x02\x03\x04 repr(x)[2:-1], produces a str object that will print as wish. In particular, repr(b'\x01')[2:-1] returns the string \\x01, while decode() will return \x01 which does not work as one would wish with print(). To be even more explicit, print(repr(b'\x01')[2:-1]) will print \x01 while print(b'\x01'.decode()) will not print anything.print(repr(b"\x01".decode()))will print '\x01' (a string including the single quotes ), so that print(repr(b"\x01".decode())[1:-1]) prints \x01 (a string without the single quotes ).bytes.__repr__ is great, but the recommendation of print(repr(x)[2:-1]) is pretty darn ugly! Not a fan of the proposed solution, although this answer is very educational.If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
>>> print(str(b"hello", "utf-8")) hello 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")) b'1337' >>> print(str(hexlify(b"\x13\x37"), "utf-8")) 1337 >>> from codecs import encode # alternative >>> print(str(encode(b"\x13\x37", "hex"), "utf-8")) 1337 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. print(data) 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()) i know this has been answered but
encoded = str(encoded).replace('b', '', 1) str(encoded)[2:-1]