Python3.3中的str转换为bytes

3

如何从'\xe3\x81\x82'获取b'\xe3\x81\x82'

最终,我想要表示日文字母'あ'的u'\u3042'

b'\xe3\x81\x82'.decode('utf-8')可以生成u'\u3042',但是

'\xe3\x81\x82'.decode('utf-8')会导致以下错误:

AttributeError: 'str' object has no attribute 'decode'

因为b'\xe3\x81\x82'是字节,而'\xe3\x81\x82'是字符串。
我有一个包含'\xe3\x81\x82'数据的数据库。
1个回答

4
如果您的字节被伪装成Unicode代码点,请编码为Latin-1:
'\xe3\x81\x82'.encode('latin1').decode('utf-8')

Latin-1 (ISO-8859-1)将Unicode代码点一对一地映射到字节:

>>> '\xe3\x81\x82'.encode('latin1').decode('utf-8')
'あ'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接