Poo*_*rna 9 python unicode utf-8
我有一组UTF-8八位字节,我需要将它们转换回unicode代码点.我怎么能在python中做到这一点.
例如,UTF-8八位字节['0xc5','0x81']应转换为0x141代码点.
Lau*_*ves 14
在Python 3.x中,str
是Unicode文本的类,bytes
用于包含八位字节.
如果用"八位字节"你真的是指'0xc5'形式的字符串(而不是'\ xc5')你可以转换成bytes
这样:
>>> bytes(int(x,0) for x in ['0xc5', '0x81'])
b'\xc5\x81'
Run Code Online (Sandbox Code Playgroud)
然后,您可以str
使用str
构造函数转换为(即:Unicode)...
>>> str(b'\xc5\x81', 'utf-8')
'?'
Run Code Online (Sandbox Code Playgroud)
...或致电.decode('utf-8')
在上bytes
对象:
>>> b'\xc5\x81'.decode('utf-8')
'?'
>>> hex(ord('?'))
'0x141'
Run Code Online (Sandbox Code Playgroud)
在3.x之前,str
类型是一个字节数组,unicode
用于Unicode文本.
同样,如果通过"八位字节"你真的是指'0xc5'形式的字符串(而不是'\ xc5')你可以像这样转换它们:
>>> ''.join(chr(int(x,0)) for x in ['0xc5', '0x81'])
'\xc5\x81'
Run Code Online (Sandbox Code Playgroud)
然后,您可以转换为unicode
使用构造函数...
>>> unicode('\xc5\x81', 'utf-8')
u'\u0141'
Run Code Online (Sandbox Code Playgroud)
...或致电.decode('utf-8')
在str
:
>>> '\xc5\x81'.decode('utf-8')
u'\u0141'
Run Code Online (Sandbox Code Playgroud)
在可爱的3.x中,所有str
的都是Unicode,并且bytes
是以前str
的:
>>> s = str(bytes([0xc5, 0x81]), 'utf-8')
>>> s
'?'
>>> ord(s)
321
>>> hex(ord(s))
'0x141'
Run Code Online (Sandbox Code Playgroud)
这就是你要求的.
归档时间: |
|
查看次数: |
23858 次 |
最近记录: |