使用变量打印原始字节

时间:2017-06-07 15:09:20

标签: python byte

!解决!

在python 2命令行中运行:

>>> print r"\x72"
\x72

python将返回:\ x72 但如果我这样做:

>>> a = "\x72"
>>> print a
r

它将打印“r”。我也知道如果我这样做:

>>> a = r"\x72"
>>> print a
\x72

但我希望能够做的是:

>>> a = "\x72"

然后制作它以便我可以打印出来,就像它一样:

r"\x73"

如何转换?

编辑: 我打印从服务器收到的字节。

工作解决方案:

def byte_pbyte(data):
    # check if there are multiple bytes
    if len(str(data)) > 1:
        # make list all bytes given
        msg = list(data)
        # mark which item is being converted
        s = 0
        for u in msg:
            # convert byte to ascii, then encode ascii to get byte number
            u = str(u).encode("hex")
            # make byte printable by canceling \x
            u = "\\x"+u
            # apply coverted byte to byte list
            msg[s] = u
            s = s + 1
        msg = "".join(msg)
    else:
        msg = data
        # convert byte to ascii, then encode ascii to get byte number
        msg = str(msg).encode("hex")
        # make byte printable by canceling \x
        msg = "\\x"+msg
    # return printable byte
    return msg

2 个答案:

答案 0 :(得分:3)

感谢ginginsha,我能够创建一个将字节转换为可打印字节的函数:

def byte_pbyte(data):
    # check if there are multiple bytes
    if len(str(data)) > 1:
        # make list all bytes given
        msg = list(data)
        # mark which item is being converted
        s = 0
        for u in msg:
            # convert byte to ascii, then encode ascii to get byte number
            u = str(u).encode("hex")
            # make byte printable by canceling \x
            u = "\\x"+u
            # apply coverted byte to byte list
            msg[s] = u
            s = s + 1
        msg = "".join(msg)
    else:
        msg = data
        # convert byte to ascii, then encode ascii to get byte number
        msg = str(msg).encode("hex")
        # make byte printable by canceling \x
        msg = "\\x"+msg
    # return printable byte
    return msg

答案 1 :(得分:2)

这可能与python : how to convert string literal to raw string literal?

重复

我认为你想要的是逃避你的逃避序列被解释。

a = '\\x72'

为了打印完整的\x72

相关问题