简体   繁体   中英

Print Raw Bytes Using Variable

!Solved!

In the python 2 command line by running:

>>> print r"\x72"
\x72

python will return: \\x72 But if I do:

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

it will print "r". I am also aware that if I do:

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

But what I want to be able to do is to take:

>>> a = "\x72"

and make it so I can print it as if it were:

r"\x73"

How do I convert that?

Edit: I am printing bytes received from a server.

Working Solution:

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

Thanks to ginginsha I was able to make a function that converts bytes into printable bytes:

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

This might be a duplicate of python : how to convert string literal to raw string literal?

I think what you want is to escape your escape sequence from being interpreted.

a = '\\x72'

In order to have it print the full \\x72

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM