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

好久不见. 提交于 2019-12-04 03:34:09

问题


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

I've tried to use z = x.replace("0", "\\"), but that causes z = '\\x32' and len(z) == 4. How can I achieve this?


回答1:


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



回答2:


Try this:

z = x[2:].decode('hex')



回答3:


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


来源:https://stackoverflow.com/questions/42463940/how-to-convert-hexadecimal-string-to-character-with-that-code-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!