为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2021-03-10 09:45:20
只需发布此内容,以便以后查找即可,因为它总是让我感到困惑:$ python3.2Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) [GCC 4.5.2] on linux2Type "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'前缀的二进制()字符串?
查看完整描述

3 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

用途decode:


print(curses.version.decode())

# 2.2


查看完整回答
反对 回复 2021-03-26
?
莫回无

TA贡献1865条经验 获得超7个赞

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

sys.stdout.buffer.write(data)

或者

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


查看完整回答
反对 回复 2021-03-26
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

如果数据采用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


查看完整回答
反对 回复 2021-03-26
  • 3 回答
  • 0 关注
  • 331 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号