繁体   English   中英

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

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

只是张贴这个以便我以后可以搜索它,因为它似乎总是让我难堪:

$ 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'"

作为问题:如何在没有b'前缀的情况下在 Python 3 中打印二进制( bytes )字符串?

使用decode

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

如果字节已经使用了适当的字符编码; 你可以直接打印它们:

sys.stdout.buffer.write(data)

要么

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

如果数据采用 UTF-8 兼容格式,则可以将字节转换为字符串。

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

如果数据尚未与 UTF-8 兼容,则可以选择先转换为十六进制。 例如,当数据是实际的原始字节时。

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

如果我们看一下bytes.__repr__的来源,它看起来好像b''被烘焙到方法中。

最明显的解决方法是从结果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

您可以使用此代码显示或打印:

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

您可以使用它进行编码或保存:

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

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

print(outputCode.decode())

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

你只需要使用 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)

默认情况下有些字节无法解码(以图片为例),因此base64会将这些字节编码为可以解码为字符串的字节,检索字节只需使用

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

使用decode()而不是encode()将字节转换为字符串。

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

暂无
暂无

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

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