字符集转换

Posted on 2017-12-20 23:54  阿骏骏  阅读(174)  评论(0编辑  收藏  举报

任何除unicode以外的字符集相互转换前都需要先decode成unicode,通过unicode再encode成目标字符集。在Python3.x中encode时会把原字符变成Bytes类型。引用该博客:http://www.cnblogs.com/luotianshuai/p/5735051.html?_t=t

import sys
print(sys.getdefaultencoding())
#字符前加U表示unicode编码
s = u'你好'
#转成gbk编码
print(s.encode('gbk'))
#decode不加参数,默认用unicode解码
#print(s.encode('gbk').decode()) #报错,因为s的字符集是gbk
#转成unicode
print(s.encode('gbk').decode('gbk'))
View Code

 

Copyright © 2024 阿骏骏
Powered by .NET 8.0 on Kubernetes