Ale*_*x T 31 python string unicode type-conversion python-3.x
我有一个代码,这样:
a = "\u0432"
b = u"\u0432"
c = b"\u0432"
d = c.decode('utf8')
print(type(a), a)
print(type(b), b)
print(type(c), c)
print(type(d), d)
Run Code Online (Sandbox Code Playgroud)
并输出:
<class 'str'> ?
<class 'str'> ?
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432
Run Code Online (Sandbox Code Playgroud)
为什么在后一种情况下我看到的是字符代码,而不是字符?我如何将Byte字符串转换为Unicode字符串,在输出的情况下,我看到了字符而不是代码?
Len*_*bro 45
在字符串(或Python 2中的Unicode对象)中,\u有一个特殊含义,即说"这里有一个由Unicode ID指定的Unicode字符".因此u"\u0432"会产生角色.
该b''前缀告诉你这是8位字节序列,和字节对象没有任何Unicode字符,所以该\u代码有没有特殊的含义.因此,b"\u0432"是字节只是序列\,u,0,4,3和2.
基本上,您有一个8位字符串,不包含Unicode字符,但包含Unicode字符的规范.
您可以使用unicode转义编码器转换此规范.
>>> c.decode('unicode_escape')
'?'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46071 次 |
| 最近记录: |