在Python中将十六进制字符转换为Unicode字符
十六进制字符串 '\xd3'
也可以表示为: Ó
。
我发现将十六进制字符串转换成字符并在控制台上显示的最简单方法是:
print unichr(ord('\xd3'))
简单来说,就是先把十六进制字符串转换成一个数字,然后再把这个数字转换成一个unicode编码点,最后把它显示出来。这样做似乎多了一步。有没有更简单的方法呢?
3 个回答
1
不久前,我遇到了一个非常相似的问题。我需要解码一些文件,这些文件里面包含的是 unicode十六进制(比如 _x0023_
),而不是直接的特殊字符(比如 #
)。解决这个问题的方法在下面的代码中有描述:
脚本
from collections import OrderedDict
import re
def decode_hex_unicode_to_latin1(string: str) -> str:
hex_unicodes = list(OrderedDict.fromkeys(re.findall(r'_x[?:\da-zA-Z]{4}_', string)))
for code in hex_unicodes:
char = bytes.fromhex(code[2:-1]).decode("latin1")[-1]
string = string.replace(code, char)
return string
def main() -> None:
string = "|_x0020_C_x00f3_digo_x0020_|"
decoded_string = decode_hex_unicode_to_latin1(string)
print(string, "-->", decoded_string)
return
if __name__ == '__main__':
main()
输出
|_x0020_C_x00f3_digo_x0020_| --> | Código |
1
如果数据看起来像这样 "\xe0\xa4\xb9\xe0\xa5\x88\xe0\xa4\xb2\xe0\xa5\x8b \xe0\xa4\x95\xe0\xa4\xb2"
sys.stdout.buffer.write(data)
那么会输出
हैलो कल
13
print u'\xd3'
你只需要做这些。你只要告诉Python这是一个unicode字面量;前面的u
就是用来表示这个的。即使是多个字符也可以这样处理。
如果你不是在谈论字面量,而是在谈论一个变量:
codepoints = '\xd3\xd3'
print codepoints.decode("latin-1")
补充说明:在print
的时候指定一个特定的编码,如果这个编码和你的终端编码不兼容,是没用的。所以就让print
自动使用encode(sys.stdout.encoding)
吧。感谢@ThomasK。