如何使用转义码\u编码Python 3字符串?

2024-06-08 12:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3中,假设我有

>>> thai_string = 'สีเ'

使用encode可以得到

^{pr2}$

我的问题是:如何让encode()使用\u而不是{}返回{}序列?如何将它们还原为python3str类型?在

我尝试使用ascii内置函数,它可以

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

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

{a1}告诉我

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

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


Tags: 函数类型stringascii序列解码字符内置
1条回答
网友
1楼 · 发布于 2024-06-08 12:17:41

您可以使用unicode_escape

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

请注意,encode()将始终返回一个字节字符串(字节)和unicode_escape编码is intended to

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

相关问题 更多 >