Mic*_*rie 6 python unicode unicode-escapes python-3.x
在Python 3中,假设我有
>>> thai_string = '???'
Run Code Online (Sandbox Code Playgroud)
使用encode
给出
>>> thai_string.encode('utf-8')
b'\xe0\xb8\xaa\xe0\xb8\xb5'
Run Code Online (Sandbox Code Playgroud)
我的问题:如何使用而不是使用encode()
返回bytes
序列?我怎么能回到Python 3 类型呢?\u
\x
decode
str
我尝试使用ascii
内置,这给了
>>> ascii(thai_string)
"'\\u0e2a\\u0e35'"
Run Code Online (Sandbox Code Playgroud)
但这似乎不太正确,因为我无法解码它以获得thai_string
.
Python文档告诉我
\xhh
转义字符与十六进制值hh
,而\uxxxx
使用16位十六进制值转义字符 xxxx
文档说\u
只用在字符串文字中,但我不确定这意味着什么.这是否暗示我的问题有一个有缺陷的前提?
你可以使用unicode_escape
:
>>> thai_string.encode('unicode_escape')
b'\\u0e2a\\u0e35\\u0e40'
Run Code Online (Sandbox Code Playgroud)
请注意,encode()
将始终返回字节字符串(字节),unicode_escape
编码旨在:
在Python源代码中生成一个适合作为Unicode文字的字符串
归档时间: |
|
查看次数: |
3213 次 |
最近记录: |