我有一个密码:
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)
输出:
<class 'str'> в
<class 'str'> в
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432
为什么在后一种情况下,我看到的是字符代码,而不是字符? 如何将字节字符串转换为Unicode字符串,以便在输出时看到字符而不是其代码?
喜欢伦纳特的回答。它使我走上了解决我所面临的特殊问题的正确道路。我添加的是能够为您生成与html兼容的代码????字符串中的规范。基本上,只需要一行:
这一切都是因为需要将JSON结果转换为在浏览器中显示良好的结果。下面是一些与云应用程序集成的测试代码:
在字符串(或Python 2中的Unicode对象)中,
\u
有一个特殊的含义,即“这里有一个由它的Unicode ID指定的Unicode字符”。因此u"\u0432"
将产生字符b。前缀
b''
告诉您这是一个8位字节的序列,bytes对象没有Unicode字符,因此\u
代码没有特殊含义。因此,b"\u0432"
只是字节\
、u
、0
、4
、3
和2
的序列。实际上,8位字符串不包含Unicode字符,而是包含Unicode字符的规范。
可以使用unicode转义编码器转换此规范。
相关问题 更多 >
编程相关推荐