簡體   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