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

前端 未结 3 1706
灰色年华
灰色年华 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:35

    The ability to include code points like '\x32' inside a quoted string is a convenience for the programmer that only works in literal values inside the source code. Once you're manipulating strings in memory, that option is no longer available to you, but there are other ways of getting a character into a string based on its code point value.

    Also note that '\x32' results in exactly the same string as '2'; it's just typed out differently.

    Given a string containing a hexadecimal literal, you can convert it to its numeric value with int(str,16). Once you have a numeric value, you can convert it to the character with that code point via chr(). So putting it all together:

    x = '0x32'
    print(chr(int(x,16)))
    #=> 2
    

提交回复
热议问题