十六进制字符串'\xd3'
也可以表示为:Ó
。
我发现将该十六进制字符串的字符表示打印到控制台最简单的方法是:
print unichr(ord('\xd3'))
换句话说,将十六进制字符串转换为数字,然后将该数字转换为Unicode代码点,最后将其输出到屏幕上。这似乎是多余的步骤。有更简单的方法吗?
print u'\xd3'
这就是你需要做的全部。你只需要以某种方式告诉Python它是一个unicode文本;前导的u
就可以做到这一点。它甚至适用于多个字符。
如果你不是在谈论一个文本,而是一个变量:
codepoints = '\xd3\xd3'
print codepoints.decode("latin-1")
编辑:如果指定特定的编码方式进行 print
不起作用,如果与您的终端编码不兼容,请让 print
自动执行 encode(sys.stdout.encoding)
。感谢 @ThomasK。
如果数据是这样的"\xe0\xa4\xb9\xe0\xa5\x88\xe0\xa4\xb2\xe0\xa5\x8b \xe0\xa4\x95\xe0\xa4\xb2"
。sys.stdout.buffer.write(data)
हैलो कल
_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 |
decoded_string = re.sub(r'_x([a-fA-F0-9]{4})_', lambda x: bytes.fromhex(x.group(1)).decode("utf-8"), string)
来重写那个循环。 - Wiktor Stribiżew
u
不是一个函数,它是字符串字面量语法的一部分。但是什么是“由代码点组成的字符串”? - Thomas Kprint u'\xd3'.encode("latin-1")
是错误的-在UTF-8终端上,根本什么也不会显示。 - Thomas Kre
库来处理Unicode。Matthew Barnett的regex库适用于Python2和Python3,这对于解决问题非常有帮助。请参见我的Unicode支持Shootout演讲第6张幻灯片上的图表,以了解MRAB的regex
库比普通的Pythonre
更好得多。然而,在UCS-²⁄₄上,您仍然会遇到Python的致命多重人格障碍。 - tchrist