0

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?

wovano
  • 4,543
  • 5
  • 22
  • 49
RoNAPC
  • 155
  • 2
  • 9
  • 2
    https://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal – vroomfondel Jun 07 '17 at 15:12
  • So you want `a = "\x72"` to print out as if it were `r"\x73"`? That doesn't make sense because a `print(r"\x73")` results in `\x73` being printed. – martineau Jun 07 '17 at 15:22
  • well the main thing I am trying to do is to print bytes received from a socket. So I don't have control over the input. the input in my case is going to be actual bytes from a server. – RoNAPC Jun 12 '17 at 18:20

2 Answers2

3

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
RoNAPC
  • 155
  • 2
  • 9
2

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

ginginsha
  • 142
  • 1
  • 11