【问题标题】:Is there any function to get utf-8 encoding output text in python?是否有任何函数可以在 python 中获取 utf-8 编码输出文本?
【发布时间】:2020-03-24 20:46:07
【问题描述】:

如何获取 utf-8 编码文本的输出? 比如 "hi" 它是编码 "\x68\x69" 的输出 如何在 python 中打印“\x68\x69”? 比如本站https://mothereff.in/utf-8#

UTF-8 解码:

你好

UTF-8 编码:

\x68\x69\x20\x74\x68\x65\x72\x65

【问题讨论】:

  • Hmm.... 所以这里使用术语“UTF-8 编码”是非常可疑的。你真正想要的是转义十六进制 -> stackoverflow.com/questions/29275085 。 mothereff.in 确实在页面上没有说明,这确实造成了损害,这些转义序列可以在 JavaScript 中使用,以编码为 UTF-8 的 JavaScript 字符串。
  • 您是否能够提供到目前为止您已完成的工作以及未正确完成的工作?请参考How do I ask a good questionHow to create a Minimal, Complete, and Verifiable example
  • @Zv_ODD JavaScript 字符串不是 UTF-8。该工具采用 Unicode 字符串并打印其 UTF-8 编码的字节序列,格式为 \x41\x42\x43
  • 我的错误,我以为我已经阅读了 JS 规范,内部有字符串为 UTF-8。这是不正确的。

标签: python utf-8


【解决方案1】:

获取 UTF-8 字节的字符串:

data = 'hi'.encode('utf-8')

打印数据字节产量:

>>> print(data)
b'hi'

打印每个字节的十六进制值:

>>> [*map(hex, data)]
['0x68', '0x69']

或者,等效地:

>>> [f'\\x{x:02x}' for x in data]
['\\x68', '\\x69']

要以您的格式获得结果,请加入每个十六进制值:

>>> print(''.join(f'\\x{x:02x}' for x in data))
\x68\x69

【讨论】:

  • 顺便说一句,[*map(hex, data)] 真的不习惯。只需使用list(map(hex, data)),其他符号用于[foo, bar, *some_iterable, baz]
  • @juanpa.arrivillaga [*map(f, data)] 便于探索性编码,更容易转换到[x for x in data] 并返回。所以 -1 对任何认为它不是惯用语的人。
猜你喜欢
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2014-01-09
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
相关资源
最近更新 更多