如何使用 u 转义码对 Python 3 字符串进行编码? [英] How to encode Python 3 string using u escape code?

查看:48
本文介绍了如何使用 u 转义码对 Python 3 字符串进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3 中,假设我有

<预><代码>>>>thai_string = 'สีเ'

使用 encode 给出

<预><代码>>>>thai_string.encode('utf-8')b'xe0xb8xaaxe0xb8xb5'

我的问题:如何让 encode() 使用 u 而不是 x<返回 bytes 序列/代码>?我如何将它们decode 恢复为 Python 3 str 类型?

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

<预><代码>>>>ascii(thai_string)"'\u0e2a\u0e35'"

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

Python 文档告诉我

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

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

解决方案

可以使用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

这篇关于如何使用 u 转义码对 Python 3 字符串进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆