简体   繁体   中英

Suppress/ print without b' prefix for bytes in Python 3

Just posting this so I can search for it later, as it always seems to stump me:

$ python3.2
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> print(curses.version)
b'2.2'
>>> print(str(curses.version))
b'2.2'
>>> print(curses.version.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
>>> print(str(curses.version).encode('utf-8'))
b"b'2.2'"

As question: how to print a binary ( bytes ) string in Python 3, without the b' prefix?

Use decode :

print(curses.version.decode())
# 2.2

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

sys.stdout.buffer.write(data)

or

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.

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

Optionally convert to hex first, if the data is not already UTF-8 compatible. Eg when the data are actual raw bytes.

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

If we take a look at the source for bytes.__repr__ , it looks as if the b'' is baked into the method.

The most obvious 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

you can use this code for showing or print :

<byte_object>.decode("utf-8")

and you can use this for encode or saving :

<str_object>.encode('utf-8')

我有点晚了,但是对于 Python 3.9.1 这对我有用并删除了 -b 前缀:

print(outputCode.decode())

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())

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM