【发布时间】:2016-10-12 08:40:55
【问题描述】:
我正在使用 python 2.7.9 将 unicode hex 转换为 unicode 文本,但我被以下代码卡住了:
text = '0421'
converted_text = ''.join([chr(int(''.join(c), 16)) for c in zip(text[0::4], text[1::4], text[2::4], text[3::4])])
print converted_text
ValueError: chr() arg not in range(256)
当我删除 chr() 时:
converted_text = ''.join([int(''.join(c), 16) for c in zip(text[0::4], text[1::4], text[2::4], text[3::4])])
TypeError: sequence item 0: expected string, int found
如果我尝试使用其他文本,例如“00DD”,它可以正常工作。 知道我的代码有什么问题吗?
【问题讨论】:
-
尝试使用
str(...)而不是chr(...)。 -
实际上
str(int(text, 16))给出了相同的结果。 -
可以使用字符串方法
.decode。在你的情况下,你会做text.decode('hex') -
str() 没有帮助,导致 chr() 将十进制转换为格式为 '\x' 的 unicode 字符。
-
text.decode('hex') 解决了我的问题,在这种情况下我不需要' '.join(....)。谢谢!