简体   繁体   English

在 Python 3 中不带 b' 前缀的字节抑制/打印

[英]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?作为问题:如何在没有b'前缀的情况下在 Python 3 中打印二进制( bytes )字符串?

Use decode :使用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.如果数据采用 UTF-8 兼容格式,则可以将字节转换为字符串。

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

Optionally convert to hex first, if the data is not already UTF-8 compatible.如果数据尚未与 UTF-8 兼容,则可以选择先转换为十六进制。 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.如果我们看一下bytes.__repr__的来源,它看起来好像b''被烘焙到方法中。

The most obvious workaround is to manually slice off the b'' from the resulting repr() :最明显的解决方法是从结果repr()手动切掉b''

>>> 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)太简单了...(有了它,您可以对字典进行编码并列出字节,然后您可以使用 json.dump / json.dumps 对其进行字符串化)

You just need use base64你只需要使用 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默认情况下有些字节无法解码(以图片为例),因此base64会将这些字节编码为可以解码为字符串的字节,检索字节只需使用

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

Use decode() instead of encode() for converting bytes to a string.使用decode()而不是encode()将字节转换为字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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