猿问

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

只需发布此内容,以便以后查找即可,因为它总是让我感到困惑:


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

问题:如何bytes在Python 3中打印不带b'前缀的二进制()字符串?


心有法竹
浏览 332回答 3
3回答

撒科打诨

用途decode:print(curses.version.decode())# 2.2

莫回无

如果字节已经使用适当的字符编码;您可以直接打印它们:sys.stdout.buffer.write(data)或者nwritten&nbsp;=&nbsp;os.write(sys.stdout.fileno(),&nbsp;data)&nbsp;&nbsp;#&nbsp;NOTE:&nbsp;it&nbsp;may&nbsp;write&nbsp;less&nbsp;than&nbsp;len(data)&nbsp;bytes

慕尼黑8549860

如果数据采用UTF-8兼容格式,则可以将字节转换为字符串。>>> import curses>>> print(str(curses.version, "utf-8"))2.2如果数据尚不兼容UTF-8,则可以选择先转换为十六进制。例如,当数据是实际的原始字节时。from binascii import hexlifyfrom codecs import encode&nbsp; # 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
随时随地看视频慕课网APP

相关分类

Python
我要回答