Skip to main content
 首页 » 编程设计

python之从 Python unicode 字符串中获取 UTF-8 字符编码

2024年10月25日26lyj

我正在从命令行读取一个字符串,我知道它是用韩语编码为 UTF-8 的。我通过运行这样的命令来获取字符串

<my_command> | od -t x1 

这给了我:

0000000 ec a7 80 ec 97 ad 2f ea b5 ad ea b0 80 0a 
0000016 

六个 UTF-8 字符是 {eca780}{ec97ad}{2f}{eab5ad}{eab080}{0a} 然后我使用 Python 读取它

utf8_str = unicode(text_from_the_cl, encoding='utf-8') 

我只想做的是能够根据我读取的字符的 UTF-8 代码查看我读取的字符串。所以像 \uc9c0\uc5ed/\uad6d\uac00 这样的东西会很好。这只是为了检查它们是否被正确读入。

(我还应该指出,这是 Python 2.6.x - 我无法控制它)

请您参考如下方法:

如果您想验证unicode 字符串的内容,请使用repr() function :

>>> from binascii import unhexlify 
>>> unhexlify(''.join('ec a7 80 ec 97 ad 2f ea b5 ad ea b0 80 0a'.split())) 
'\xec\xa7\x80\xec\x97\xad/\xea\xb5\xad\xea\xb0\x80\n' 
>>> print unhexlify(''.join('ec a7 80 ec 97 ad 2f ea b5 ad ea b0 80 0a'.split())).decode('utf8') 
지역/국가 
 
>>> print repr(unhexlify(''.join('ec a7 80 ec 97 ad 2f ea b5 ad ea b0 80 0a'.split())).decode('utf8')) 
u'\uc9c0\uc5ed/\uad6d\uac00\n' 

unicode 值的 repr() 结果对非 ASCII 和非 Latin1 代码点使用 \uhhhh 转义序列;对于 Latin 1 代码点和不可打印的字符,使用 \xhh 转义序列。