如何用该代码点将十六进制字符串转换为字符? [英] How to convert hexadecimal string to character with that code point?
问题描述
我有字符串x = '0x32'
,想将其转换为y = '\x32'
.
请注意len(x) == 4
和len(y) == 1
.
I have the string x = '0x32'
and would like to turn it into y = '\x32'
.
Note that len(x) == 4
and len(y) == 1
.
我尝试使用z = x.replace("0", "\\")
,但这会导致z = '\\x32'
和len(z) == 4
.我该如何实现?
I've tried to use z = x.replace("0", "\\")
, but that causes z = '\\x32'
and len(z) == 4
. How can I achieve this?
推荐答案
您不必那么费劲:您可以使用int(..,16)
来解析形式为0x...
的十六进制字符串.接下来,您只需使用chr(..)
将该数字转换为具有Unicode的字符(并且如果代码小于128 ASCII):
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))
结果是:
>>> chr(int(x,16))
'2'
但是\x32
等于'2'
(您可以在ASCII表中查找它):
But \x32
is equal to '2'
(you can look it up in the ASCII table):
>>> chr(int(x,16)) == '\x32'
True
和:
>>> len(chr(int(x,16)))
1
这篇关于如何用该代码点将十六进制字符串转换为字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!