python中编码unicode和utf-8

来源:互联网 发布:淘宝有哪些女装潮店 编辑:程序博客网 时间:2024/05/31 06:24

在python中的字符串内存中是用unicode进行编码
python2

>>> s="我爱你python">>> su=u"我爱你python">>> s.encode("utf-8")Traceback (most recent call last):  File "<stdin>", line 1, in <module>UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinalnot in range(128)>>> s.decode("gb2312").encode("utf-8")'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0python'

原因是s字符串在window中默认是gb2312,要把它decode成unicode编码,然后encode成utf-8,在encode的时候一定要保证该字符串是unicode,如果直接调用encode会首先默认调用系统的编码进行decode
系统默认编码

>>> import sys>>> sys.getdefaultencoding()'ascii'

在python3中

>>> s="我爱你python">>> s.encode("utf-8")b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0python'

默认s字符串是unicode
这里写图片描述

原创粉丝点击