How to convert hexadecimal string to character with that code point?

前端 未结 3 1730
灰色年华
灰色年华 2021-01-19 04:07

I have the string x = \'0x32\' and would like to turn it into y = \'\\x32\'.
Note that len(x) == 4 and len(y) == 1.

3条回答
  •  独厮守ぢ
    2021-01-19 04:53

    You do not have to make it that hard: you can use int(..,16) to parse a hex string of the form 0x.... Next you simply use chr(..) to convert that number into a character with that Unicode (and in case the code is less than 128 ASCII) code:

    y = chr(int(x,16))
    

    This results in:

    >>> chr(int(x,16))
    '2'
    

    But \x32 is equal to '2' (you can look it up in the ASCII table):

    >>> chr(int(x,16)) == '\x32'
    True
    

    and:

    >>> len(chr(int(x,16)))
    1
    

提交回复
热议问题