![](/img/trans.png)
[英]How to correctly represent a supplementary unicode char in python3 (3.6.1+) by using \u or \U escape within string
[英]How to encode Python 3 string using \u escape code?
在Python 3中,假设我有
>>> thai_string = 'สีเ'
使用encode
给出
>>> thai_string.encode('utf-8')
b'\xe0\xb8\xaa\xe0\xb8\xb5'
我的问题:如何使用
\\u\u003c/code>而不是
\\x
来使encode()
返回bytes
序列? 我怎样才能
decode
它们decode
回Python 3 str
类型?
我尝试使用
ascii
builtin,它给出了
>>> ascii(thai_string)
"'\\u0e2a\\u0e35'"
但这似乎不太正确,因为我无法解码它以获得
thai_string
。
Python文档告诉我
\\xhh
以十六进制值hh
转义字符
\\uxxxx
使用16位十六进制值xxxx
转义字符
文档说
\\u\u003c/code>仅用于字符串文字,但我不确定这意味着什么。
这是否暗示我的问题有一个有缺陷的前提?
你可以使用unicode_escape
:
>>> thai_string.encode('unicode_escape')
b'\\u0e2a\\u0e35\\u0e40'
请注意, encode()
将始终返回字节字符串(字节), unicode_escape
编码旨在 :
在Python源代码中生成一个适合作为Unicode文字的字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.