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

标签 python encoding utf-8 python-2.6

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

相关文章:

python - 无法在 tensorboard 中使用 summary.merge 进行单独的培训和评估摘要

php - MySQL插入改变编码

c++ - Qt 应用程序不打印 ěčř

javascript - 如何解码字符实体引用

c++ - 如何正确地将 USC-2 little endian 转换为 UTF-8?

从另一个文件返回函数时的 Python 问题

python - 在 linux 中运行 python 可执行文件

java - LayoutWrappingEncoder 的 LogBack 默认字符集?

go - 为什么不使用 go 1.10 编译器编译,但可以在 go playground 上运行

python - [Microsoft][ODBC Driver 17 for SQL Server]登录超时已过期 (0) (SQLDriverConnect)')