【问题标题】:How to encode Python 3 string using \u escape code?如何使用 \u 转义码对 Python 3 字符串进行编码?
【发布时间】:2015-11-23 16:30:48
【问题描述】:

在 Python 3 中,假设我有

>>> thai_string = 'สีเ'

使用encode 给出

>>> thai_string.encode('utf-8')
b'\xe0\xb8\xaa\xe0\xb8\xb5'

我的问题:如何让encode() 使用\u 而不是\x 返回bytes 序列?我怎样才能decode 他们回到 Python 3 str 类型?

我尝试使用 ascii 内置函数,它给出了

>>> ascii(thai_string)
"'\\u0e2a\\u0e35'"

但这似乎不太正确,因为我无法将其解码回来以获取thai_string

Python documentation 告诉我

  • \xhh 使用十六进制值 hh 转义字符,而
  • \uxxxx 使用 16 位十六进制值 xxxx 转义字符

文档说\u 仅用于字符串文字,但我不确定这意味着什么。这是否暗示我的问题有一个有缺陷的前提?

【问题讨论】:

标签: python python-3.x unicode unicode-escapes


【解决方案1】:

你可以使用unicode_escape:

>>> thai_string.encode('unicode_escape')
b'\\u0e2a\\u0e35\\u0e40'

注意encode()总是会返回一个字节串(bytes)和unicode_escape编码is intended to

在 Python 源代码中生成一个适合作为 Unicode 文字的字符串

【讨论】:

  • 完美。但是为什么这个字符串的“u”前面有两个斜杠,而“x”只有一个呢?
  • 这就是 Python 在带引号的字符串中显示文字反斜杠的简单方式。比较'\\n'(文字反斜杠,文字n)和'\n'(换行符)。
  • 如果你想要结果为字符串,你可以附加.decode('ascii')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 2010-10-16
  • 2010-10-26
  • 2012-08-23
  • 2015-09-18
相关资源
最近更新 更多