gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:13 24 4
gpt4 key购买 nike

我正在从命令行读取一个字符串,我知道它是用韩语编码为 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 转义序列。

关于python - 从 Python unicode 字符串中获取 UTF-8 字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com