在Python 3中打印字节时强制转义可打印字符 [英] Forcing escaping of printable characters when printing bytes in Python 3

查看:69
本文介绍了在Python 3中打印字节时强制转义可打印字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个字节对象

I have a bytes object, for instance

test = b'\x83\xf8\x41\x41\x41'

我想将此对象打印到stdout,但如果这样做,Python会将对象中的可打印字符转换为ASCII:

I would like to print this object to stdout, but if I do, Python converts the printable characters in the object to ASCII:

print(test)
b'\x83\xf8AAA'

是否有一种方法可以强制Python 3将可打印字符(在本例中为三个'A')打印为转义字节?

Is there a way to force Python 3 to print the printable characters (in this instance, three 'A's) as escaped bytes?

也就是这样,以便 print(test)输出

b'\x83\xf8\x41\x41\x41'

推荐答案

否, repr()输出不可配置;这是一个调试工具.

No, the repr() output is not configurable; it is a debug tool.

您可以使用 binascii.hexlify() 以获取十六进制表示形式:

You could use binascii.hexlify() to get a hex representation:

>>> test = b'\x83\xf8\x41\x41\x41'
>>> from binascii import hexlify
>>> test = b'\x83\xf8\x41\x41\x41'
>>> print(hexlify(test))
b'83f8414141'

或者您可以将每个字节"值转换为十六进制表示形式:

or you could convert each individual 'byte' value to a hex representation:

>>> print("b'{}'".format(''.join('\\x{:02x}'.format(b) for b in test)))
b'\x83\xf8\x41\x41\x41'

这会产生另一种表示形式.

This produces an alternative representation.

这篇关于在Python 3中打印字节时强制转义可打印字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆