且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 u 转义码对 Python 3 字符串进行编码?

更新时间:2023-02-17 19:29:32

可以使用unicode_escape:

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

请注意,encode() 将始终返回一个字节字符串 (bytes) 和 unicode_escape 编码 旨在:

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

In Python 3, suppose I have

>>> thai_string = 'สีเ'

Using encode gives

>>> thai_string.encode('utf-8')
b'xe0xb8xaaxe0xb8xb5'

My question: how can I get encode() to return a bytes sequence using u instead of x? And how can I decode them back to a Python 3 str type?

I tried using the ascii builtin, which gives

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

But this doesn't seem quite right, as I can't decode it back to obtain thai_string.

Python documentation tells me that

  • xhh escapes the character with the hex value hh while
  • uxxxx escapes the character with the 16-bit hex value xxxx

The documentation says that u is only used in string literals, but I'm not sure what that means. Is this a hint that my question has a flawed premise?

You can use unicode_escape:

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

Note that encode() will always return a byte string (bytes) and the unicode_escape encoding is intended to:

Produce a string that is suitable as Unicode literal in Python source code